How to get an ALAsset URL from a PHAsset?

后端 未结 5 1128
灰色年华
灰色年华 2020-11-27 06:36

You can do it sneakily† using the undocumented PHAsset.ALAssetURL property, but I\'m looking for something documented.


† In Objective-C, this will

5条回答
  •  生来不讨喜
    2020-11-27 07:12

    Here is a PHAsset extension written in Swift that will retrieve the URL.

    extension PHAsset {
    
        func getURL(completionHandler : @escaping ((_ responseURL : URL?) -> Void)){
            if self.mediaType == .image {
                let options: PHContentEditingInputRequestOptions = PHContentEditingInputRequestOptions()
                options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData) -> Bool in
                    return true
                }
                self.requestContentEditingInput(with: options, completionHandler: {(contentEditingInput: PHContentEditingInput?, info: [AnyHashable : Any]) -> Void in
                    completionHandler(contentEditingInput!.fullSizeImageURL as URL?)
                })
            } else if self.mediaType == .video {
                let options: PHVideoRequestOptions = PHVideoRequestOptions()
                options.version = .original
                PHImageManager.default().requestAVAsset(forVideo: self, options: options, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable : Any]?) -> Void in
                    if let urlAsset = asset as? AVURLAsset {
                        let localVideoUrl: URL = urlAsset.url as URL
                        completionHandler(localVideoUrl)
                    } else {
                        completionHandler(nil)
                    }
                })
            }
        }
    }
    

提交回复
热议问题