Determine if the access to photo library is set or not - PHPhotoLibrary

后端 未结 11 793
误落风尘
误落风尘 2020-11-27 10:23

With the new functionality in iOS 8, if you are using a camera in the app, it will ask for permission to access the camera and then when you try to retake the pic, it asks f

相关标签:
11条回答
  • 2020-11-27 10:48
    I have a simple solution on swift 2.0
    
    //
    //  AppDelegate.swift
    //  HoneyBadger
    //
    //  Created by fingent on 14/08/15.
    //  Copyright (c) 2015 fingent. All rights reserved.
    //
    
    import UIKit
    import Photos
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
            self.window?.makeKeyAndVisible()
    
                 self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginPageID")
                self.window?.rootViewController = initialViewController
                self.window?.makeKeyAndVisible()
            return true
        }
        func applicationDidEnterBackground(application: UIApplication) {
            print("Application On background", terminator: "")
        }
        func applicationDidBecomeActive(application: UIApplication) {
            cameraAllowsAccessToApplicationCheck()
            photoLibraryAvailabilityCheck()
        }
        //MARK:- CAMERA ACCESS CHECK
        func cameraAllowsAccessToApplicationCheck()
        {
            let authorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
            switch authorizationStatus {
            case .NotDetermined:
                // permission dialog not yet presented, request authorization
                AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo,
                    completionHandler: { (granted:Bool) -> Void in
                        if granted {
                            print("access granted", terminator: "")
                        }
                        else {
                            print("access denied", terminator: "")
                        }
                })
            case .Authorized:
                print("Access authorized", terminator: "")
            case .Denied, .Restricted:
                alertToEncourageCameraAccessWhenApplicationStarts()
            default:
                print("DO NOTHING", terminator: "")
            }
        }
        //MARK:- PHOTO LIBRARY ACCESS CHECK
        func photoLibraryAvailabilityCheck()
        {
            if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.Authorized
            {
    
            }
            else
            {
                PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler)
            }
        }
        func requestAuthorizationHandler(status: PHAuthorizationStatus)
        {
            if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.Authorized
            {
    
            }
            else
            {
                alertToEncouragePhotoLibraryAccessWhenApplicationStarts()
            }
        }
    
        //MARK:- CAMERA & GALLERY NOT ALLOWING ACCESS - ALERT
        func alertToEncourageCameraAccessWhenApplicationStarts()
        {
            //Camera not available - Alert
            let internetUnavailableAlertController = UIAlertController (title: "Camera Unavailable", message: "Please check to see if it is disconnected or in use by another application", preferredStyle: .Alert)
    
            let settingsAction = UIAlertAction(title: "Settings", style: .Destructive) { (_) -> Void in
                let settingsUrl = NSURL(string:UIApplicationOpenSettingsURLString)
                if let url = settingsUrl {
                    dispatch_async(dispatch_get_main_queue()) {
                        UIApplication.sharedApplication().openURL(url)
                    }
    
                }
            }
            let cancelAction = UIAlertAction(title: "Okay", style: .Default, handler: nil)
            internetUnavailableAlertController .addAction(settingsAction)
            internetUnavailableAlertController .addAction(cancelAction)
            self.window?.rootViewController!.presentViewController(internetUnavailableAlertController , animated: true, completion: nil)
        }
        func alertToEncouragePhotoLibraryAccessWhenApplicationStarts()
        {
    //Photo Library not available - Alert
            let cameraUnavailableAlertController = UIAlertController (title: "Photo Library Unavailable", message: "Please check to see if device settings doesn't allow photo library access", preferredStyle: .Alert)
    
            let settingsAction = UIAlertAction(title: "Settings", style: .Destructive) { (_) -> Void in
                let settingsUrl = NSURL(string:UIApplicationOpenSettingsURLString)
                if let url = settingsUrl {
                    UIApplication.sharedApplication().openURL(url)
                }
            }
            let cancelAction = UIAlertAction(title: "Okay", style: .Default, handler: nil)
            cameraUnavailableAlertController .addAction(settingsAction)
            cameraUnavailableAlertController .addAction(cancelAction)
            self.window?.rootViewController!.presentViewController(cameraUnavailableAlertController , animated: true, completion: nil)
        }
    }
    
    0 讨论(0)
  • 2020-11-27 10:48

    Swift 2.0+

    Based on a combination of answers here, I've created a solution for myself. This method only checks if there is no permission.

    We got a method pickVideo() that requires access to photos. If it is not .Authorized ask for permission.

    If permission is not given, pickVideo() will not be called, and the user cannot pick a video.

    As long as the user did not give full access to photos, you can avoid to let them pick 'or crash' your application.

      // Method that requires access to photos
      func pickVideo(){
        // Check for permission
        if PHPhotoLibrary.authorizationStatus() != .Authorized{
          // If there is no permission for photos, ask for it
          PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler)
          return
        }
        //... pick video code here...
      }
    
      func requestAuthorizationHandler(status: PHAuthorizationStatus){
        if PHPhotoLibrary.authorizationStatus() == .Authorized{
          // The user did authorize, so, pickVideo may be opened
          // Ensure pickVideo is called from the main thread to avoid GUI problems
          dispatch_async(dispatch_get_main_queue()) {
            pickVideo()
          }
        } else {
          // Show Message to give permission in Settings
          let alertController = UIAlertController(title: "Error", message: "Enable photo permissions in settings", preferredStyle: .Alert)
          let settingsAction = UIAlertAction(title: "Settings", style: .Default) { (alertAction) in
            if let appSettings = NSURL(string: UIApplicationOpenSettingsURLString) {
              UIApplication.sharedApplication().openURL(appSettings)
            }
          }
          alertController.addAction(settingsAction)
          // If user cancels, do nothing, next time Pick Video is called, they will be asked again to give permission
          let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
          alertController.addAction(cancelAction)
          // Run GUI stuff on main thread
            dispatch_async(dispatch_get_main_queue()) {      
              self.presentViewController(alertController, animated: true, completion: nil)
            }
          }
        }
    
    0 讨论(0)
  • 2020-11-27 10:54

    Just as formality, Swift 2.X version:

        func checkPhotoLibraryPermission() {
           let status = PHPhotoLibrary.authorizationStatus()
           switch status {
           case .Authorized:
                //handle authorized status
           case .Denied, .Restricted :
                //handle denied status
           case .NotDetermined:
                // ask for permissions
                PHPhotoLibrary.requestAuthorization() { (status) -> Void in
                   switch status {
                   case .Authorized:
                       // as above
                   case .Denied, .Restricted:
                       // as above
                   case .NotDetermined:
                       // won't happen but still
                   }
                }
            }
        }
    

    And Swift 3 / Swift 4:

        import Photos
    
        func checkPhotoLibraryPermission() {
            let status = PHPhotoLibrary.authorizationStatus()
            switch status {
            case .authorized: 
            //handle authorized status
            case .denied, .restricted : 
            //handle denied status
            case .notDetermined: 
                // ask for permissions
                PHPhotoLibrary.requestAuthorization { status in
                    switch status {
                    case .authorized: 
                    // as above
                    case .denied, .restricted: 
                    // as above
                    case .notDetermined: 
                    // won't happen but still
                    }
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-27 10:55

    Check +[PHPhotoLibrary authorizationStatus] – if not set, it will return PHAuthorizationStatusNotDetermined. (You can then request access using +requestAuthorization: on the same class.)

    0 讨论(0)
  • 2020-11-27 10:58

    iOS 14 onwards Apple has added a new feature that will give limited access to the photos library. Based on your requirements (Example creating custom photo gallery) you have to check if user has given limited access only and wants to give full access.

    For backwards compatibility, the old versions without the parameter return .authorized even when you get limited access.

    Swift 5:

    switch PHPhotoLibrary.authorizationStatus(for: .readWrite) {
    case .notDetermined:
        // ask for access
    case .restricted, .denied:
        // sorry
    case .authorized:
        // we have full access
     
    // new option: 
    case .limited:
        // we only got access to some photos of library
    }
    

    There is a code to call limited access screen again. if user has given .limited access only and you want user to select the images again.

    PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: presentVCObj)
    

    On every restart of app iOS will show alert to notify user about the limited access. If you want to stop that alert then add PHPhotoLibraryPreventAutomaticLimitedAccessAlert to YES in Info.plist

    0 讨论(0)
  • 2020-11-27 10:59

    Here is a small and simple snippet that I usually use.

    - (void)requestPhotoAuthorization:(void (^)(BOOL granted))granted
    {
        void (^handler)(PHAuthorizationStatus) = ^(PHAuthorizationStatus status)
        {
            if (status == PHAuthorizationStatusAuthorized) granted(YES);
            else if (status == PHAuthorizationStatusNotDetermined) [PHPhotoLibrary requestAuthorization:handler];
            else granted(NO);
        };
        handler([PHPhotoLibrary authorizationStatus]);
    }
    
    0 讨论(0)
提交回复
热议问题