Ask permission to access Camera Roll

后端 未结 7 1272
生来不讨喜
生来不讨喜 2020-11-28 22:39

I have a settings view where the user can choose switch on or off the feature \'Export to Camera Roll\'

When the user switches it on for the first time (and

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 22:46

    Since iOS 10 we also need to provide photo library usage description in info.plist file which I described there. And then just use this code to make alert appear everytime we need:

    - (void)requestAuthorizationWithRedirectionToSettings {
        dispatch_async(dispatch_get_main_queue(), ^{
            PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
            if (status == PHAuthorizationStatusAuthorized)
            {
                //We have permission. Do whatever is needed
            }
            else
            {
                //No permission. Trying to normally request it
                [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                    if (status != PHAuthorizationStatusAuthorized)
                    {
                        //User don't give us permission. Showing alert with redirection to settings
                        //Getting description string from info.plist file
                        NSString *accessDescription = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSPhotoLibraryUsageDescription"];
                        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:accessDescription message:@"To give permissions tap on 'Change Settings' button" preferredStyle:UIAlertControllerStyleAlert];
    
                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
                        [alertController addAction:cancelAction];
    
                        UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"Change Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                        }];
                        [alertController addAction:settingsAction];
    
                        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
                    }
                }];
            }
        });
    }
    

    Also there are some common cases when alert doesn't appear. To avoid copying I would like you to take a look at this answer.

提交回复
热议问题