Created
November 3, 2021 05:46
-
-
Save sindresorhus/b37c9ab01b79b754ca1690aaa266c410 to your computer and use it in GitHub Desktop.
How to use `PHImageManager#requestImage` with async/await in Swift.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Photos | |
struct UnexpectedNilError: Error {} | |
extension PHImageManager { | |
func requestImage( | |
for asset: PHAsset, | |
targetSize: CGSize, | |
contentMode: PHImageContentMode, | |
options: PHImageRequestOptions? | |
) async throws -> UIImage { | |
options?.isSynchronous = false | |
var requestID: PHImageRequestID? | |
return try await withTaskCancellationHandler( | |
handler: { [requestID] in | |
guard let requestID = requestID else { | |
return | |
} | |
cancelImageRequest(requestID) | |
} | |
) { | |
try await withCheckedThrowingContinuation { continuation in | |
requestID = requestImage( | |
for: asset, | |
targetSize: targetSize, | |
contentMode: contentMode, | |
options: options | |
) { image, info in | |
if let error = info?[PHImageErrorKey] as? Error { | |
continuation.resume(throwing: error) | |
return | |
} | |
guard !(info?[PHImageCancelledKey] as? Bool ?? false) else { | |
continuation.resume(throwing: CancellationError()) | |
return | |
} | |
// When degraded image is provided, the completion handler will be called again. | |
guard !(info?[PHImageResultIsDegradedKey] as? Bool ?? false) else { | |
return | |
} | |
guard let image = image else { | |
// This should in theory not happen. | |
continuation.resume(throwing: UnexpectedNilError()) | |
return | |
} | |
// According to the docs, the image is guaranteed at this point. | |
continuation.resume(returning: image) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Won't it simply capture an empty copy of requestID on line 17?