iosobjective-calassetslibrary

App crash: when writeVideoAtPathToSavedPhotosAlbum using ALAssetsLibrary


We are making a chat app and for video thumbnail we use the following code. But it crashes in random cases.

NSArray *arrjid = [jid componentsSeparatedByString:@"@"];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *strdate = [dateFormatter stringFromDate:[NSDate date]];
NSString *strname = [NSString stringWithFormat:@"%@_%@_file.mov",arrjid[0],strdate];
NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:strname];
[videoData writeToFile:videoPath atomically:YES];

if([[NSFileManager defaultManager] fileExistsAtPath:videoPath])
{
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:videoPath] completionBlock:^(NSURL *assetURL, NSError *error) {
    }];
}

Every time it crashes on the writeVideoAtPathToSavedPhotosAlbum line and it gives only "bad access error".

Does anyone have an idea related to this?


Solution

  • ALAssetsLibrary library method writeVideoAtPathToSavedPhotosAlbum:completionBlock: is deprecated, you can use PHPhotoLibrary instead.

    try this

    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL: yourVideoURlHere];
    } completionHandler:^(BOOL success, NSError *error) {
        if (success) {
            //Do Something   
        }
    }];
    

    Also check if you have Photo Library usage description in info plist with following key

    NSPhotoLibraryUsageDescription
    

    UPDATE

    For fetching thumbnail from video you can use AVAssetImageGenerator class from AVFoundation framework

    - (UIImage *) thumbnailFromVideoAtURL:(NSURL *) contentURL {
        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:contentURL options:nil];
        AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        generator.appliesPreferredTrackTransform = YES;
        NSError *err = NULL;
        CMTime time = CMTimeMake(1, 60);
        CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&err];
        UIImage *thumbnail = [[UIImage alloc] initWithCGImage:imgRef];
        CGImageRelease(imgRef);
    
        return thumbnail;
    }