0
4

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】macOSアプリで保存機能を作成する

Posted at

はじめに

最近、Macアプリを作っているのですが、保存機能を作成しようと思った時にやり方がわからなかったので記録しておきます。

サンプルアプリ

画面収録_2023-02-09_23_05_34_AdobeExpress.gif

ファイルへのアクセス権を付与

① プロジェクトを選択します
② ターゲットを選択します
③ 「Signing & Capabilities」を選択します
④ 「File Access Type」の「User Selected File」のピッカーを選択します
スクリーンショット 2023-02-09 23.14.01.png

⑤ 「Read/Write」を選択します
スクリーンショット 2023-02-09 23.17.30.png

実装方法

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Button {
                showSavePanel()
            } label: {
                Text("Download")
            }
        }
        .frame(width: 300, height: 200)
    }

    func showSavePanel() {
        let savePanel = NSSavePanel()
        savePanel.message = "Download"
        savePanel.allowedContentTypes = [.png]
        guard let window = NSApp.windows.first else { return }
        savePanel.beginSheetModal(for: window) { response in
            switch response {
            case .OK:
                guard let path = savePanel.url else { return }
                saveImage(imageName: "sample", path: path)
            default:
                break
            }
        }
    }

    func saveImage(imageName: String, path: URL) {
        guard let image = NSImage(named: imageName),
              let representation = image.tiffRepresentation
        else { return }
        let imageRep = NSBitmapImageRep(data: representation)
        guard let png = imageRep?.representation(using: .png, properties: [:]) else { return }
        try? png.write(to: path)
    }
}

スクリーンショット 2023-02-09 23.19.30.png

おわり

よく見る保存画面を実装することができました!

0
4
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
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?