How can I write a file in a folder located at Apple's Files App in SwiftUI?

后端 未结 2 571
孤独总比滥情好
孤独总比滥情好 2021-01-25 01:30

I followed the Swift project UsingFiles github and its video to write files in my SwiftUI project. The project UsingFiles can write files to Files APP and then the writing files

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 02:21

    I used UIActivityViewController to save a file on my phone. It's simple and works.

    import SwiftUI
    
    struct ContentView: View {
    
        var body: some View {
            Button(action: wirtieFile) {
                Image(systemName: "square.and.arrow.up")
            }
        }
    
        func wirtieFile() -> Void{
            let file = "test.txt"
            let dir = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(file)
            let contents = "test..."
            do {
               try contents.write(to: dir!, atomically: true, encoding: .utf8)
            } catch {
               print(error.localizedDescription)
            }
            var filesToShare = [Any]()
            filesToShare.append(dir!)
            let av = UIActivityViewController(activityItems: filesToShare, applicationActivities: nil)
            UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)
        }
    }
    

提交回复
热议问题