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

后端 未结 11 846
误落风尘
误落风尘 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条回答
  •  旧时难觅i
    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)
            }
          }
        }
    

提交回复
热议问题