iOS14选择相册适配问题。
在iOS14之后新增了
Limited Photo Library Access
模式,在授权弹窗中增加了 Select Photo 选项(如图1,就是第一个选项 ‘选择照片...’)。
选中之后就跳转到系统的PHPickerViewController
进行选择图片(如图2)。
如果不适配会导致一些问题。
图1 | 图2 |
---|---|
具体解决方案,更新API。然后在调用相机的时候,判断一下是否是limited。如果是的话,我们就给一个提示(让他去更改权限提示),并且可以让用户选择重新选择可用的照片,具体代码如下:
在iOS 14新增两个API,要更新一下
/// accessLevel 我们选择 readWrite 就行了
@available(iOS 14, *) //获取当前相册权限 accessLevel是权限等级
open class func authorizationStatus(for accessLevel: PHAccessLevel) -> PHAuthorizationStatus
@available(iOS 14, *) //发起相册权限请求 accessLevel是权限等级
open class func requestAuthorization(for accessLevel: PHAccessLevel, handler: @escaping (PHAuthorizationStatus) -> Void)
然后在你的相册中添加下面判断代码
var authorizationStatus = PHPhotoLibrary.authorizationStatus()
if #available(iOS 14, *) {
authorizationStatus = PHPhotoLibrary.authorizationStatus(for: .readWrite)
}
if #available(iOS 14, *) {
if authorizationStatus == .limited {
//这里可以添加提示 。代码我就不放了如图3
//还可以添加UIAlertController选择弹框,点击 选择更多照片... 调用下面代码。如图4
//[[PHPhotoLibrary sharedPhotoLibrary] presentLimitedLibraryPickerFromViewController:self];
}
}
点击 选择更多照片... 调用下面代码。如图4
[[PHPhotoLibrary sharedPhotoLibrary] presentLimitedLibraryPickerFromViewController:self];
图3 | 图4 |
---|---|
假如你就简单的改变一个头像,推荐PHPickerViewController
,这iOS14之后官方推荐的。可选images,videos,livePhotos
等
if #available(iOS 14.0, *) {
var configuration = PHPickerConfiguration.init()
configuration.filter = PHPickerFilter.any(of: [PHPickerFilter.images,PHPickerFilter.videos,PHPickerFilter.livePhotos])
configuration.selectionLimit = 1
let picker = PHPickerViewController.init(configuration: configuration)
picker.delegate = self
picker.view.backgroundColor = UIColor.blue
picker.modalPresentationStyle = .fullScreen
self.present(picker, animated: true) {
}
}
//MARK: PHPickerViewControllerDelegate
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
if results.count == 0 {
return
}
let itemProvider = results.first?.itemProvider
if itemProvider?.canLoadObject(ofClass: UIImage.classForCoder() as! NSItemProviderReading.Type) == true {
itemProvider?.loadObject(ofClass: UIImage.classForCoder() as! NSItemProviderReading.Type, completionHandler: { object, error in
print(object as Any)
})
}
//在回调中调用消失方法
picker.dismiss(animated: true) {
}
}