Skip to content

Instantly share code, notes, and snippets.

@eleev
Last active February 17, 2024 23:56
Show Gist options
  • Save eleev/2f041bb8b1936093773f0bde42af3a49 to your computer and use it in GitHub Desktop.
Save eleev/2f041bb8b1936093773f0bde42af3a49 to your computer and use it in GitHub Desktop.
Getting URL for PHAsset (Swift 3.0)
func getURL(ofPhotoWith mPhasset: PHAsset, completionHandler : @escaping ((_ responseURL : URL?) -> Void)) {
if mPhasset.mediaType == .image {
let options: PHContentEditingInputRequestOptions = PHContentEditingInputRequestOptions()
options.canHandleAdjustmentData = {(adjustmeta: PHAdjustmentData) -> Bool in
return true
}
mPhasset.requestContentEditingInput(with: options, completionHandler: { (contentEditingInput, info) in
completionHandler(contentEditingInput!.fullSizeImageURL)
})
} else if mPhasset.mediaType == .video {
let options: PHVideoRequestOptions = PHVideoRequestOptions()
options.version = .original
PHImageManager.default().requestAVAsset(forVideo: mPhasset, options: options, resultHandler: { (asset, audioMix, info) in
if let urlAsset = asset as? AVURLAsset {
let localVideoUrl = urlAsset.url
completionHandler(localVideoUrl)
} else {
completionHandler(nil)
}
})
}
}
@eleev
Copy link
Author

eleev commented Jun 22, 2020

@freemansion greatly appreciate for pointing that important case out.

@fernandodev
Copy link

Thanks! I slightly changed it for what i need

    func requestAssetUrl() -> AnyPublisher<URL, Error> {
        Future { [self] promise in
            if self.mediaType == .image {
                self.requestContentEditingInput(with: nil) { input, info in
                    if let input = input, let url = input.fullSizeImageURL {
                        promise(.success(url))
                    } else {
                        promise(.failure(Errors.urlNotAvailable))
                    }
                }
            } else if self.mediaType == .video {
                let options: PHVideoRequestOptions = PHVideoRequestOptions()
                options.version = .original
                PHImageManager.default().requestAVAsset(forVideo: self, options: options) { asset, audio, info in
                    if let urlAsset = asset as? AVURLAsset {
                        let localVideoUrl = urlAsset.url
                        promise(.success(localVideoUrl))
                    } else {
                        promise(.failure(Errors.urlNotAvailable))
                    }
                }
            } else {
                promise(.failure(Errors.mediaNotSupported))
            }
        }.eraseToAnyPublisher()
    }
    
    extension PHAsset {
      enum Errors: Error {
          case urlNotAvailable
          case mediaNotSupported
      }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment