SwiftUI exporting or sharing files

后端 未结 5 702
再見小時候
再見小時候 2021-01-12 21:53

I\'m wondering if there is a good way export or share a file through SwiftUI. There doesn\'t seem to be a way to wrap a UIActivityViewController and present it directly. I\'

5条回答
  •  太阳男子
    2021-01-12 22:31

    Take a look at AlanQuatermain -s SwiftUIShareSheetDemo

    In a nutshell it looks like this:

    @State private var showShareSheet = false
    @State public var sharedItems : [Any] = []
    
    Button(action: {
        self.sharedItems = [UIImage(systemName: "house")!]
        self.showShareSheet = true
    }) {
        Text("Share")
    }.sheet(isPresented: $showShareSheet) {
        ShareSheet(activityItems: self.sharedItems)
    }
    
    struct ShareSheet: UIViewControllerRepresentable {
        typealias Callback = (_ activityType: UIActivity.ActivityType?, _ completed: Bool, _ returnedItems: [Any]?, _ error: Error?) -> Void
    
        let activityItems: [Any]
        let applicationActivities: [UIActivity]? = nil
        let excludedActivityTypes: [UIActivity.ActivityType]? = nil
        let callback: Callback? = nil
    
        func makeUIViewController(context: Context) -> UIActivityViewController {
            let controller = UIActivityViewController(
                activityItems: activityItems,
                applicationActivities: applicationActivities)
            controller.excludedActivityTypes = excludedActivityTypes
            controller.completionWithItemsHandler = callback
            return controller
        }
    
        func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {
            // nothing to do here
        }
    }
    

提交回复
热议问题