How to access Asset Catalog (images) after downloaded through NSBundleResourceRequest?

532 views Asked by At

I cannot access images inside an asset catalog after it's been downloaded through NSBundleResourceRequest (on demand resource).

My code, say the image set name is "snow_4" with on demand resource tag "tag1"

NSBundleResourceRequest* resourceRequest = [[NSBundleResourceRequest alloc] initWithTags:[NSSet setWithObjects:@"tag1", nil]];

[resourceRequest conditionallyBeginAccessingResourcesWithCompletionHandler:
 ^(BOOL resourcesAvailable){
     // if resource is not available download it
     if (!resourcesAvailable) {
         [resourceRequest beginAccessingResourcesWithCompletionHandler:
          ^(NSError * __nullable error){
              if(!error){                      
                  UIImage* image = [UIImage imageNamed:@"snow_4"]; // image is null
              }
          }];
     }else{             
         UIImage* image = [UIImage imageNamed:@"snow_4"]; // image is null
     }
 }];

Below is my Disk Report, please note that [UIImage imageNamed:@"snow_3"] (marked as 'In Use') returns a correct object but not images that are marked as 'Downloaded'

Disk Report

Appreciating your time and help!

Thanks, Mars

3

There are 3 answers

1
vince On

do this

image = [UIImage imageNamaed:@"snow_4" inBundle:[resourceRequest bundle]];

0
D.Ter On

Make sure NSBundleResourceRequest is not released early. Try to let NSBundleResourceRequest variable globally, and access the image with UIImage(named: "xxx", in: self.bundleReq.bundle, compatibleWith: nil)

0
uwei On
let tags = NSSet(array: ["tag1","tag2"])
let resourceRequest = NSBundleResourceRequest(tags: tags as! Set<String>)
resourceRequest.conditionallyBeginAccessingResourcesWithCompletionHandler {(resourcesAvailable: Bool) -> Void in
    if resourcesAvailable {
        // Do something with the resources
    } else {
        resourceRequest.beginAccessingResourcesWithCompletionHandler {(err: NSError?) -> Void in
            if let error = err {
                print("Error: \(error)")
            } else {
                // Do something with the resources
            }
        }
    }
}