App crash: when writeVideoAtPathToSavedPhotosAlbum using ALAssetsLibrary

421 Views Asked by At

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?

2

There are 2 best solutions below

2
Jabson On BEST ANSWER

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;
}
0
birdman On

Make sure you have permission to save to the photo gallery.

Import the Photos class:

#import <Photos/Photos.h>

Then check for Photo Library Authorization

PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];

if (status == PHAuthorizationStatusAuthorized) {
    //OK to save your video
    [self ContinueDownload];
}
else if (status == PHAuthorizationStatusDenied) {
    // Access has been denied.
    [self ShowAlert];
}
else if (status == PHAuthorizationStatusNotDetermined) {

    // Access has not been determined.
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

        if (status == PHAuthorizationStatusAuthorized) {
             //OK to save your video
            [self ContinueDownload];
        }
        else {
            // Access has been denied.
            [self ShowAlert];
        }
    }];
}
else if (status == PHAuthorizationStatusRestricted) {
    // Restricted access
}

//Show an alert if access is denied
-(void)ShowAlert {
    UIAlertController * alert = [UIAlertController
                                 alertControllerWithTitle:@"Gallery Access denied"
                                 message:@"You can grant access in\nSettings/Privacy/Photos\nif you change your mind."
                                 preferredStyle:UIAlertControllerStyleAlert];



    UIAlertAction* OKButton = [UIAlertAction
                               actionWithTitle:@"OK"
                               style:UIAlertActionStyleDefault
                               handler:^(UIAlertAction * action) {
                                   //[self dismissViewControllerAnimated:YES completion:nil];
                               }];

    [alert addAction:OKButton];

    [self presentViewController:alert animated:YES completion:nil];

}