Created
May 1, 2024 15:44
-
-
Save takoikatakotako/191308b3c4a793b7c4205c289bcb3fe0 to your computer and use it in GitHub Desktop.
iOSのファイルアプリ(UIDocumentPickerViewController)を開いてドキュメントフォルダに保存したファイルを開く
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct ContentView: View { | |
@State private var fileUrl: URL? | |
@State private var showingPicker = false | |
var body: some View { | |
VStack { | |
Button { | |
let documentDirectoryUrl = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask ).first! | |
let fileUrl = documentDirectoryUrl.appendingPathComponent("snorlax.txt") | |
try! "I Love Snorlax!".data(using: .utf8)!.write(to: fileUrl, options: .atomic) | |
} label: { | |
Text("Save File to Document") | |
} | |
Button { | |
showingPicker = true | |
} label: { | |
Text("Show File Picker") | |
} | |
Text("FileUrl: \(fileUrl?.description ?? "nil")") | |
} | |
.sheet(isPresented: $showingPicker) { | |
DocumentPickerView(fileUrl: $fileUrl) | |
} | |
} | |
} | |
#Preview { | |
ContentView() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
import UniformTypeIdentifiers | |
struct DocumentPickerView : UIViewControllerRepresentable { | |
@Binding var fileUrl: URL? | |
class Coordinator: NSObject, UIDocumentPickerDelegate { | |
var parent: DocumentPickerView | |
init(_ parent: DocumentPickerView) { | |
self.parent = parent | |
} | |
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { | |
self.parent.fileUrl = url | |
} | |
} | |
func makeUIViewController(context: Context) -> UIDocumentPickerViewController { | |
let documentPickerViewController = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.text]) | |
documentPickerViewController.delegate = context.coordinator | |
return documentPickerViewController | |
} | |
func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {} | |
func makeCoordinator() -> Coordinator { | |
Coordinator(self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment