3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】画像(UIImage)をpngファイルとしてiPhoneに保存する

Last updated at Posted at 2021-11-28

#何の記事?

SwiftUIで写真を撮影するアプリを作っているのですが、カメラロールに保存された写真には名前を付けることができません。そこで、画像をiPhoneの本体に名前付きで保存できるようにします。

この記事の情報は次のバージョンで動作確認しています。
【Xcode】13.1
【Swift】5.5.1
【iOS】15.1
【macOS】Big OS Monterey 12.1

#iosアプリのファイルシステム

iOSアプリは、システムが不正に操作されるのを防ぐ為、アクセスできるフォルダがアプリ毎に隔離されています。これをSandbox構造と呼びます。対象のフォルダは、端末からアプリを削除すると一緒に削除されます。

Mac本体とiPhoneとを接続すると、Finderからファイルシステムにアクセスすることができます。アプリごとにフォルダ分けされていることがわかります。

#アプリにファイルを書き込みするためには

    //private func saveToDoc (image: UIImage, fileName: String ) -> Bool{
    public func SaveToDoc () -> Bool{
         let pngImageData = UIImage.pngData(image)
               //iPhone内ファイルシステムのURLを取得
        let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
               //ファイル名をつなげる
        let fileURL = documentsURL.appendingPathComponent("test.png")
              //保存
        do {
            try pngImageData()!.write(to: fileURL)
            print("SaveToDoc Done!")
        } catch {
            //エラー処理
            return false
        }
        return true
    }

#権限の設定
上記スクリプトによりエラーなく実行できますが、権限を設定しておかないとファイルシステム内にアプリのフォルダが作成されません。必要な設定は下の2つです。
・Supports opening documents in place
・Application supports iTunes file sharing
image.png

これらの設定後にアプリを起動させると、ファイルシステム内に新しいフォルダが作成されました。test.pngも無事に保存されていますね。
image.png

参考:
https://develop.hateblo.jp/entry/iosapp-uiimage-save
https://capibara1969.com/2836/

3
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?