首页 > 解决方案 > 如何从 PHPickerViewController 委托获取实时照片或视频

问题描述

Apple 的新 iOS 14 PHPickerViewController 委托仅接收 NSItemProvider。2020 WWDC 视频展示了如何从那里获取 UIImage:

    let prov = result.itemProvider
    prov.loadObject(ofClass: UIImage.self) { im, err in
        if let im = im as? UIImage {
            DispatchQueue.main.async {
                // display the image here

但是,如果用户选择了实况照片或视频呢?我们如何得到它?

标签: iosphotokitios14

解决方案


现场照片很容易;以完全相同的方式进行。你可以这样做,因为 PHLivePhoto 是一个类。所以:

    let prov = result.itemProvider
    prov.loadObject(ofClass: PHLivePhoto.self) { livePhoto, err in
        if let photo = livePhoto as? PHLivePhoto {
            DispatchQueue.main.async {
                // display the live photo here

视频更难。问题是您不想收到数据;它对你没有好处,而且可能很大。您希望将数据保存到磁盘,以便您可以访问视频 URL,就像 UIImagePickerController 过去所做的那样。实际上,您可以要求项目提供者为您保存其数据,但它希望在完成处理程序返回时释放该数据。我的解决方案是在函数中访问 URL .sync

    let prov = result.itemProvider
    prov.loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier) { url, err in
        if let url = url {
            DispatchQueue.main.sync {
                // display the video here

推荐阅读