Swift 请求用户访问照片库的权限

Swift Ask for user’s permission to access the photo library

我正在尝试访问照片库以在 swift 中导入个人资料图片。

但是我得到了这个错误:

This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryUsageDescription key with a string value explaining to the user how the app uses this data.

我以各种方式请求许可。

我试试 :

<key>NSPhotoLibraryUsageDescription</key>
    <string>this permission for profile photo only</string>

和代码:

let imagePicker = UIImagePickerController()
 override func viewDidLoad() {
     super.viewDidLoad()
     imagePicker.delegate = self
}
@objc func importUserImage() {
        print("import driver")

        imagePicker.sourceType = .photoLibrary
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true)
    }

我试试

<key>NSPhotoLibraryAddUsageDescription</key>
    <string>this permission for profile photo only</string>

我什至尝试在代码中做到这一点

import UIKit
import Photos
import UserNotifications

class LoginViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        PHPhotoLibrary.requestAuthorization { (status) in
            // cruch here
        }
     }
}

我删除了应用程序并重新安装,仍然崩溃

我是不是忘记了什么?或者我做错了什么?

试试这个:

转到您的 plist。在最顶部,它应该说 Information 属性 List have this selected。然后右键单击并 添加行 类型 隐私 - 照片库添加使用说明 然后在右侧有一个值列需要输入文本你这就是用户将看到的。希望对您有所帮助!

NSPhotoLibraryUsageDescription 如果只想访问用户照片库就足够了,下面的代码可以正常工作

PHPhotoLibrary.requestAuthorization { (status) in
   // No crash
}

如果需要读写权限,请将以下两个键添加到info.plist

<key>NSPhotoLibraryUsageDescription</key>
<string>this permission for profile photo only</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>this permission for profile photo only</string>

我只是在 Project/info/Custom IOS 目标属性中添加键 NSPhotoLibraryUsageDescription 。而不是 info.plist,现在它工作正常