Home > Mobile >  How to check in Swift if the user gave permission to access the photolibrary with UIImagePicker?
How to check in Swift if the user gave permission to access the photolibrary with UIImagePicker?

Time:12-24

I am currently working on an app that give the user a preview of the last the images he had taken with his camera, but I dont know how to check if the user gave permissions to access all the images in the gallery, selected images or he denied the access.

There is a method or class I can import to check the kind of permissions the user gave to my app?

enter image description here

CodePudding user response:

You can use the below method to check the permission status for the gallery. and if the permission is denied then also it navigates you to the app setting screen.

func checkGalleryPermission()
{
    let authStatus = PHPhotoLibrary.authorizationStatus()
    switch authStatus
    {
        case .denied : print("denied status")
            let alert = UIAlertController(title: "Error", message: "Photo library status is denied", preferredStyle: .alert)
            let cancelaction = UIAlertAction(title: "Cancel", style: .default)
            let settingaction = UIAlertAction(title: "Setting", style: UIAlertAction.Style.default) { UIAlertAction in
                if let url = URL(string: UIApplication.openSettingsURLString) {
                    UIApplication.shared.open(url, options: [:], completionHandler: { _ in })
                }
            }
            alert.addAction(cancelaction)
            alert.addAction(settingaction)
            Viewcontoller.present(alert, animated: true, completion: nil)
            break
        case .authorized : print("success")
           //open gallery
            break
        case .restricted : print("user dont allowed")
            break
        case .notDetermined : PHPhotoLibrary.requestAuthorization({ (newStatus) in
                if (newStatus == PHAuthorizationStatus.authorized) {
                    print("permission granted")
                    //open gallery
                }
                else {
                    print("permission not granted")
                }
            })
            break
    case .limited:
       print("limited")
    @unknown default:
        break
    }
}
  • Related