SwiftUI exporting or sharing files

后端 未结 5 690
再見小時候
再見小時候 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:09

    You can define this function anywhere (preferably in the global scope):

    @discardableResult
    func share(
        items: [Any],
        excludedActivityTypes: [UIActivity.ActivityType]? = nil
    ) -> Bool {
        guard let source = UIApplication.shared.windows.last?.rootViewController else {
            return false
        }
        let vc = UIActivityViewController(
            activityItems: items,
            applicationActivities: nil
        )
        vc.excludedActivityTypes = excludedActivityTypes
        vc.popoverPresentationController?.sourceView = source.view
        source.present(vc, animated: true)
        return true
    }
    

    You can use this function in a button action, or anywhere else needed:

    Button(action: {
        share(items: ["This is some text"])
    }) {
        Text("Share")
    }
    

提交回复
热议问题