ライブラリの写真をPHAssetで取得して、UIImageで更新保存するサンプルです。
ググっても意外と出てこない模様なので。
ちゃんと読もう
Apple 公式のサンプル
環境
Xcode 13.0
ミニマムなサンプルコード
import UIKit
import Photos
private lazy var formatIdentifier = Bundle.main.bundleIdentifier!
private let formatVersion = "1.0"
private func update(asset: PHAsset, toPhoto: UIImage, completionHandler: @escaping ((Bool, Error?) -> Void)) {
let options = PHContentEditingInputRequestOptions()
options.canHandleAdjustmentData = { _ in
return true
}
asset.requestContentEditingInput(with: options) { input, info in
guard let input = input else { fatalError("Can't get the content-editing input: \(info)") }
DispatchQueue.global(qos: .userInitiated).async {
let output = PHContentEditingOutput(contentEditingInput: input)
let adjustmentData = PHAdjustmentData(formatIdentifier:formatIdentifier, formatVersion:formatVersion, data: "my app".data(using: .utf8)!)
output.adjustmentData = adjustmentData
let jpg = toPhoto.jpegData(compressionQuality: 0.9)
do {
try jpg?.write(to: output.renderedContentURL)
} catch let error {
fatalError("Can't save image to PHContentEditingOutput.renderedContentURL : \(error).")
}
PHPhotoLibrary.shared().performChanges {
let request = PHAssetChangeRequest(for: asset)
request.contentEditingOutput = output
} completionHandler: { success, error in
completionHandler(success, error)
}
}
}
}
なんとかしたい
- renderedContentURLに吐き出せるのがなぜかjpg一択?