2
2

More than 3 years have passed since last update.

アプリで取り扱っている画像(UIImage)を端末に保存する

Posted at

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 {
                    // ここに来ることがあるのかどうか、ちょっと調べた限りわからない…
                }
            })
    }
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2