IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> How to Manage Photo Library Permission in iOS -> 正文阅读

[移动开发]How to Manage Photo Library Permission in iOS

When Apple introduced limited photo access in iOS 14, some iOS developers were not so happy about it, it seems like Apple was trying to make developers’ life harder. Any apps (old or new) that want to support iOS 14 or higher will have to handle this extra permission status.

Meanwhile, from the user’s perspective, it is a very welcome change. Users can now have more control over the privacy of their photos, limiting the number of photos an app can access.

With this new permission status, the way to handle photo library permission in iOS 14 is very different from the previous iOS versions. In this article, I would like to show you how to properly handle each and every permission status in your iOS apps. Once you get the full picture of how it works, you will find that it is not as complicated as you think.

Note:

This article is mainly for situations where you need to build your own image picker. If you don’t need a custom image picker, use the new?PHPickerViewController?(a better?UIImagePickerController) that manages photo library permission for you.


The Sample App

In terms of photo library permission handling, I really like how Facebook App did it. Therefore, let’s try to create a simple prototype app that mimics the Facebook App’s photo library permission workflow.

Since the aim of this article is to show you how to handle each permission status, we won’t be building a fully functioning image picker. Instead, we will create a POC image picker that displays the permission status, number of accessible photos, and the required UI elements.

UIs for each authorization status

When tap on the “See All Photos” button, the app will redirect the user to the app’s privacy settings so that he/she can grant full photo library access to the app.

Tapping on “See All Photos” button

Whereas, when tapping on the “Manage” button, the user can either select more photos or grant full photo library access to the app.

Tapping on “Manage” button


Requesting Photo Library Access Permission

Before we can start accessing the user’s photo library, we must first get permission to do so. Head over to?info.plist?and add the?NSPhotoLibraryUsageDescription?key to the plist.

Adding NSPhotoLibraryUsageDescription to info.plist

Next up, import the?PhotosUI?module:

import PhotosUI

and insert the following code to our custom image picker?viewDidLoad()?method:

// Request permission to access photo library
PHPhotoLibrary.requestAuthorization(for: .readWrite) { [unowned self] (status) in
    DispatchQueue.main.async { [unowned self] in
        showUI(for: status)
    }
}

Do note that the request completion handler?does not run on the main thread, thus it is our responsibility to dispatch back to the main thread when updating the view based not the returned permission status.

Pro Tip:

In the above code, we are requesting for?.readWrite?access level. If your app only requires write access, it is recommended to add the?NSPhotoLibraryAddUsageDescription?key into?info.plist?and request authorization using?.addOnly?access level.

Within the?showUI(for:)?method, we will handle each and every possible permission status accordingly:

func showUI(for status: PHAuthorizationStatus) {
    
    switch status {
    case .authorized:
        showFullAccessUI()

    case .limited:
        showLimittedAccessUI()

    case .restricted:
        showRestrictedAccessUI()

    case .denied:
        showAccessDeniedUI()

    case .notDetermined:
        break

    @unknown default:
        break
    }
}

Following are the brief description of each permission status:

  • .authorized: The app has full access to the photo library.
  • .limited: The app only has limited access to the photo library.
  • .restricted: The user is under a configuration profile (such as parental controls) that restricts the user from accessing the photo library. In other words, the user does not have the authority to grant photo library access.
  • .denied: The user does not allow the app to access the photo library.
  • .notDetermined: The user has not set the app’s authorization status.

At this stage of implementation, if we try to show our custom image picker for the first time, it will prompt the user for photo library access permission.

One good thing about the?requestAuthorization(for:handler:)?function is that it only prompts the users when permission status is?.notDetermined. For the other permission status, the function will just trigger the completion handler by giving back the current permission status.


Handling Access Denied

If the user decided to stop our app from accessing the photo library for some reason, we can always encourage the user to change his/her mind.

What we can do is to show a “See All Photos” button to redirect the user to the app’s privacy settings so that he/she can grant photo library access to the app.

func showAccessDeniedUI() {
    manageButton.isHidden = true
    seeAllButton.isHidden = false
    
    infoLabel.text = "Status: denied"
}

By following the Facebook App workflow, when the “See All Photos” button is tapped, we will show a confirmation message telling the user what to do in order to grant photo library access to the app.

@IBAction func seeAllButtonTapped(_ sender: Any) {
    
    let alert = UIAlertController(title: "Allow access to your photos",
                                  message: "This lets you share from your camera roll and enables other features for photos and videos. Go to your settings and tap \"Photos\".",
                                  preferredStyle: .alert)
    
    let notNowAction = UIAlertAction(title: "Not Now",
                                     style: .cancel,
                                     handler: nil)
    alert.addAction(notNowAction)
    
    let openSettingsAction = UIAlertAction(title: "Open Settings",
                                           style: .default) { [unowned self] (_) in
        // Open app privacy settings
        gotoAppPrivacySettings()
    }
    alert.addAction(openSettingsAction)
    
    present(alert, animated: true, completion: nil)
}

and the last part of the puzzle is to implement the?gotoAppPrivacySettings()?method that brings the user to the app’s privacy settings:

func gotoAppPrivacySettings() {
    guard let url = URL(string: UIApplication.openSettingsURLString),
        UIApplication.shared.canOpenURL(url) else {
            assertionFailure("Not able to open App privacy settings")
            return
    }

    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Here, we do not need to observe the change in the photo’s privacy settings. This is because every time when the user updates the photo’s privacy settings, our app will relaunch and start a brand new app life cycle.


Handling Limited Access

Managing Selected Photos

When our app is in limited access mode, our app only has access to certain photos that are selected by the user. On top of that, in every app life cycle, iOS will automatically prompt a limited photos access alert the first time when the app tries to access the photo library.

The limited photos access alert

This is not what we want!

We want to have a “Manage” button that allows the user to manually trigger the limited photo library picker when he/she wants to select more photos.

In order to prevent the limited photos access alert from showing, add the?PHPhotoLibraryPreventAutomaticLimitedAccessAlert?key to?info.plist?and set its value to?YES.

Adding?PHPhotoLibraryPreventAutomaticLimitedAccessAlert?to?info.plist

After that, show the “Manage” button and the amount of photos we can access on screen.

func showLimittedAccessUI() {
    manageButton.isHidden = false
    seeAllButton.isHidden = true
    
    let photoCount = PHAsset.fetchAssets(with: nil).count
    infoLabel.text = "Status: limited\nPhotos: \(photoCount)"
}

When the “Manage” button is tapped, we will show an action sheet, asking the user to either select more photos or grant full photo library access to the app.

import PhotosUI

@IBAction func manageButtonTapped(_ sender: Any) {
    
    let actionSheet = UIAlertController(title: "",
                                        message: "Select more photos or go to Settings to allow access to all photos.",
                                        preferredStyle: .actionSheet)
    
    let selectPhotosAction = UIAlertAction(title: "Select more photos",
                                           style: .default) { [unowned self] (_) in
        // Show limited library picker
        PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: self)
    }
    actionSheet.addAction(selectPhotosAction)
    
    let allowFullAccessAction = UIAlertAction(title: "Allow access to all photos",
                                              style: .default) { [unowned self] (_) in
        // Open app privacy settings
        gotoAppPrivacySettings()
    }
    actionSheet.addAction(allowFullAccessAction)
    
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    actionSheet.addAction(cancelAction)
    
    present(actionSheet, animated: true, completion: nil)
}

With that, we have successfully implemented the workflow of managing selected photos. But how do we know that changes have been made so that we can update our custom image picker accordingly?

Observing Photo Library Change

In order to get notified when the selected photos changes, we must conform to the?PHPhotoLibraryChangeObserver?protocol and implement the?photoLibraryDidChange(_:)?method.

extension ImagePickerViewController: PHPhotoLibraryChangeObserver {
    
    func photoLibraryDidChange(_ changeInstance: PHChange) {
        DispatchQueue.main.async { [unowned self] in
            // Obtain authorization status and update UI accordingly
            let status = PHPhotoLibrary.authorizationStatus(for: .readWrite)
            showUI(for: status)
        }
    }
}

Just like the request authorization completion handler, the?photoLibraryDidChange(_:)?method does not trigger on the main thread. Therefore, remember to dispatch back to the main thread before updating our custom image picker.

With the conformance in place, all that remains is to register our custom image picker as an observer to the photo library change. Head back to the?viewDidLoad()?method and add the following line of code:

// Observe photo library changes
PHPhotoLibrary.shared().register(self)

That’s it for observing photo library change. Our custom image picker should now be able to display the correct amount of selected photos every time selected photos changes.

Updating UI after user selected new photos


Handling Full Access

As you can see from how we handle limited access, we do not straightaway present the limited library picker. Instead, we show an action sheet hinting the user to give us full library access. This is because getting full library access is the best case scenario and it is the easiest to handle.

In our custom image picker, we can basically hide all the call to action buttons and just display the photo library content:

func showFullAccessUI() {
    manageButton.isHidden = true
    seeAllButton.isHidden = true
    
    let photoCount = PHAsset.fetchAssets(with: nil).count
    infoLabel.text = "Status: authorized\nPhotos: \(photoCount)"
}

Handling Restricted Access

As mentioned earlier, the restricted status indicates that even the user itself does not have access to the photo library. Meaning nothing can be done on the app side as well:

func showRestrictedAccessUI() {
    manageButton.isHidden = true
    seeAllButton.isHidden = true
    
    infoLabel.text = "Status: restricted"
}

Wrapping Up

There you have it! Properly handling every authorization status is not as complicated as you think. Feel free to get the full sample code?here?and try it for yourself.

If you enjoy reading this article, please check out my other iOS development related?articles. You can also follow me on?Twitter,?and subscribe to my monthly newsletter.

Thanks for reading.?👨🏻?💻

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-09-04 01:23:00  更:2022-09-04 01:25:06 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/25 4:36:06-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码