Cad*_*o21 4 objective-c ios swift ios14 phpickerviewcontroller
所以,我发现之前问过类似的问题,但是当我尝试与我得到的方法相同的方法时,它没有按我的预期工作,所以我想做的是,我想从 PHPickerViewController 的 PHPickerResult 获取 PHAsset。
因此,使用此源代码作为我的基本代码进行实验,并将其与我从中获得的内容相结合。
info.plist当我尝试此操作时,还已经添加了“隐私 - 照片库使用说明” 。
代码如下所示。
import UIKit
import PhotosUI
class ViewController: UIViewController {
@IBOutlet weak var myImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func buttonDidTap(_ sender: Any) {
var configuration = PHPickerConfiguration()
configuration.selectionLimit = 1
configuration.filter = .any(of: [.images, .videos])
let picker = PHPickerViewController(configuration: configuration)
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
}
extension ViewController: PHPickerViewControllerDelegate {
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
picker.dismiss(animated: true)
let identifiers = results.compactMap(\.assetIdentifier)
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: identifiers, options: nil)
fetchResult.enumerateObjects { (asset, index, stop) -> Void in
PHImageManager.default().requestImage(for: asset,
targetSize: CGSize.init(width: 20, height: 20),
contentMode: PHImageContentMode.aspectFit,
options: nil) { (image: UIImage?, _: [AnyHashable : Any]?) in
self.myImageView.image = image
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试调试代码后,我发现里面的代码fetchResult.enumerateObjects没有被调用,这就是为什么我无法获取图像。
或者也许我的语法错误?有人能帮我吗?
如果稍后需要资产,则必须使用照片库初始化配置。所以这一行是错误的:
var configuration = PHPickerConfiguration()
Run Code Online (Sandbox Code Playgroud)
你要:
var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
Run Code Online (Sandbox Code Playgroud)