在UIImageWriteToSavedPhotosAlbum函数ios之前做一些事情

时间:2018-07-10 02:19:14

标签: ios objective-c

现在我有一个问题,如果我们无权将照片保存到相册中,则该应用程序将崩溃。因此,我想一开始就要求访问。但是,如果用户选择“否”,则该应用将在保存照片时崩溃。因此,我想在使用UIImageWriteToSavedPhotosAlbum函数之前判断我们是否具有访问权限。除了在每个UIImageWriteToSavedPhotosAlbum函数之前添加代码之外,还可以使用其他方法吗?

1 个答案:

答案 0 :(得分:0)

它崩溃了,因为您需要设置

  

NSPhotoLibraryUsageDescription

info.plist 文件中

然后使用以下代码检查图库的访问权限

PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
if (status == PHAuthorizationStatusAuthorized) {
    // Access has been granted.
    NSLog(@"Access Granted");
   UIImage *myImage = [UIImage imageNamed:@"Mobile.png"];
            UIImageWriteToSavedPhotosAlbum(myImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);


}

else if (status == PHAuthorizationStatusDenied) {
    // Access has been denied.
     NSLog(@"Access NOT Granted");
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Not Granted"
                                                                   message:@"You have not granted permission for a gallery to save photos, Please grant it from setting"
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {}];

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

}

else if (status == PHAuthorizationStatusNotDetermined) {

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

        if (status == PHAuthorizationStatusAuthorized) {
            UIImage *myImage = [UIImage imageNamed:@"Mobile.png"];
            UIImageWriteToSavedPhotosAlbum(myImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }

        else {
            // Access has been denied.
        }
    }];
}

else if (status == PHAuthorizationStatusRestricted) {
    // Restricted access - normally won't happen.
}

别忘了#import <Photos/Photos.h>

别忘了实现此方法

- (void) image:(UIImage*)image didFinishSavingWithError:(NSError *)error contextInfo:(NSDictionary*)info{
}