PHAsset Null but local identifier is valid

324 Views Asked by At

I am trying to load an asset from a local identifier. The local identifier seems to be correct but the asset is null and I can't figure out why. I have a similar code in another part of my app that works fine.

Queue *queue = [NSEntityDescription insertNewObjectForEntityForName:@"Queue" inManagedObjectContext:self.context];

for (int reyrt = 0; reyrt < self.storeGIF.count; reyrt++) {
    queue.queuetextimagePath = [self.storeGIF objectAtIndex:reyrt];

}


__block float fileSize;
NSArray *identifiers = @[queue.queuetextimagePath];
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:identifiers options:nil];
PHAsset *asset  = [assetsFetchResult firstObject];

NSLog (@"identifiers: %@", identifiers);
NSLog (@"assetsFetchResult: %@", assetsFetchResult);
NSLog (@"asset: %@", asset);
    if (!asset) {
        NSLog(@"can't retrieve PHAsset from localIdentifier:%@",identifiers);
    }

Here is the NSLog file result when using the above code.

019-07-19 09:26:36.366739-0400 myApp[1440:328144] identifiers: (
"857AC3DA-C047-4D88-911B-C5FE227E2B96/L0/001"
)

2019-07-19 09:26:36.366945-0400 myApp[1440:328144] assetsFetchResult PHFetchResult: 0x281129900 count=0

2019-07-19 09:26:36.366982-0400 myApp[1440:328144] asset: (null)

2019-07-19 09:26:36.367061-0400 myApp[1440:328144] can't retrieve PHAsset from localIdentifier:(
"857AC3DA-C047-4D88-911B-C5FE227E2B96/L0/001"
)
2

There are 2 best solutions below

1
fewlinesofcode On

The problem is that you should drop /L0/001 part before requesting the object. I don't understand why uuid strings contain these suffixes, but it works if you drop it and use only normal UUID part.

0
Sri Krishna On

Found the solution for this issue.

Root cause being the below code takes some time to complete, and immediately accessing the asset will give you nil.

// This Line takes some time to complete!    
PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:identifiers options:nil];
// Gives nil 
PHAsset *asset  = [assetsFetchResult firstObject];

Instead do this:

NSError *error = nil;
BOOL success = [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
    // The Long running code or the Asset Creation code.
    PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:identifiers options:nil];
} error:&error];
if (success) {
    // Changes were performed successfully
    PHAsset *asset  = [assetsFetchResult firstObject]; // Not nil !
} else {
    // Handle the error
    NSLog(@"Error performing changes to the Photos library: %@", error.localizedDescription);
}