UIImageViewに表示したりするのに使っている画像(UIImage)を端末のアルバムに保存したかったのでやり方を調べました。
まず、Info.plistの<dict>
の中にNSPhotoLibraryAddUsageDescription
があるか確認します。なかったら以下のように追加します。パーミッション要求時の文言は、アプリの内容に応じて指定します。
<key>NSPhotoLibraryAddUsageDescription</key>
<string>パーミッション要求時の文言</string>
そしたら、画像を保存しようとしているところで以下のような処理を実行します。
func save(image: UIImage) {
// パーミッションを確認
PHPhotoLibrary.requestAuthorization { status in
guard status == .authorized else {
// 権限がない
return
}
// 保存処理
PHPhotoLibrary.shared().performChanges(
{
// このブロック内でPHAssetCreationRequestを作成すると保存される
PHAssetCreationRequest.creationRequestForAsset(from: image)
}, completionHandler: { success, error in
if let error = error {
// エラー処理
return
} else if success {
// 保存完了
} else {
// ここに来ることがあるのかどうか、ちょっと調べた限りわからない…
}
})
}
}