Wesley de Groot's Blog
Swift Package: FilePicker

Back

FilePicker is a Swift Package to open and save files in SwiftUI. It provides a simple way to open and save files in SwiftUI views.

Installation

To install FilePicker, add it to your Package.swift file:

dependencies: [
    .package(url: "https://github.com/0xWDG/FilePicker", branch: "main")
]

Use Case: Open a file

Opening a file:

import SwiftUI
import FilePicker

struct ContentView: View {
    // MARK: Filepicker
    @State var filePickerOpen = false
    @State var filePickerFiles: [URL] = []

    var body: some View {
        VStack {
            Text("Open a file :)")
                .padding()

            Button("Open", systemImage: "square.and.arrow.down") {
                filePickerOpen.toggle()
            }

            ForEach(filePickerFiles, id: \.self) { file in
                Text(file.lastPathComponent)
            }
        }
        .padding()
        .filePicker(
            isPresented: $filePickerOpen,
            files: $filePickerFiles,
            types: [.json, .text], // Optional (default: .json)
            allowsMultipleSelection: false // Optional (default: false)
        )
        .onChange(of: $filePickerFiles.wrappedValue) { newValue in
            print(newValue)
        }
    }
}

Use Case: Save a file

import SwiftUI
import FilePicker

struct ContentView: View {
    // MARK: Filepicker
    @State var filePickerOpen = false
    var filePickerFileName = "test.txt"
    var filePickerData = Data("Hello, World!".utf8)

    var body: some View {
        VStack {
            Text("Save a file :)")
                .padding()

            Button("Save", systemImage: "square.and.arrow.up") {
                filePickerOpen.toggle()
            }
        }
        .padding()
        .filePicker(
            isPresented: $filePickerOpen,
            fileName: filePickerFileName,
            data: filePickerData,
            types: [.text]
        )
    }
}

Conclusion

FilePicker is a Swift Package to open and save files in SwiftUI. It provides a simple way to open and save files in SwiftUI views.

Resources:

Read more

Share


Share Bluesky Mastodon Twitter LinkedIn Facebook
x-twitter mastodon github linkedin discord threads instagram whatsapp bluesky square-rss sitemap