swift - 如何通过添加#available 同时使用 UIImagePickerController 和 PHPicker
问题描述
PHPickerViewController 仅受 iOS 14.0 支持。如果您的应用程序的部署目标为 iOS 13.0 及更低版本,您仍然必须使用 UIImagePickerController。我如何使用它,任何人都可以共享一些 KT
解决方案
PHPicker函数IOS14
@available(iOS 14, *)
class UIViewController : PHPickerViewControllerDelegate{
func pickPhoto(limit : Int , delegate : PHPickerViewControllerDelegate){
// new in iOS 14, we can get the asset _later_ so we don't need access up front
do {
// if you create the configuration with no photo library, you will not get asset identifiers
var config = PHPickerConfiguration()
// try it _with_ the library
config = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
config.selectionLimit = limit // default
// what you filter out will indeed not appear in the picker
config.filter = .any(of: [.images , .livePhotos]) // default is all three appear, no filter
config.preferredAssetRepresentationMode = .current
let picker = PHPickerViewController(configuration: config)
picker.delegate = delegate
// works okay as a popover but even better just present, it will be a normal sheet
self.present(picker, animated: true)
// PHPhotoLibrary.shared().presentLimitedLibraryPicker(from: self)
}
}
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
guard results.first != nil else {
picker.dismiss(animated: true, completion: nil)
return
}
picker.dismiss(animated: true) {
let prov = results.first!.itemProvider
prov.loadObject(ofClass: UIImage.self) { im, err in
if let image = im as? UIImage {
// do whatever action with your image here
}
}
}
}
UIImagePicker <iOS14
class UIViewController : UIImagePickerControllerDelegate , UINavigationControllerDelegate{
func openGallary() {
let localUIPicker = UIImagePickerController()
localUIPicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
localUIPicker.allowsEditing = false
localUIPicker.sourceType = UIImagePickerController.SourceType.photoLibrary
self.present(localUIPicker, animated: true, completion: {})
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let choosenLogo = info[.originalImage] as? UIImage else {
return
}
// do whatever action with your image here
}
}
如何使用
// This Function call will launch picker according to compatible iOS version
func showPhotos() {
if #available(iOS 14, *) {
pickPhoto(limit: 1, delegate: self)
} else {
// Fallback on earlier versions
openGallary()
}
print("open photoLibary")
}