SwiftUI exporting or sharing files

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

    We can call the UIActivityViewController directly from the View (SwiftUI) without using UIViewControllerRepresentable.

    import SwiftUI
    enum Coordinator {
      static func topViewController(_ viewController: UIViewController? = nil) -> UIViewController? {
        let vc = viewController ?? UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController
        if let navigationController = vc as? UINavigationController {
          return topViewController(navigationController.topViewController)
        } else if let tabBarController = vc as? UITabBarController {
          return tabBarController.presentedViewController != nil ? topViewController(tabBarController.presentedViewController) : topViewController(tabBarController.selectedViewController)
          
        } else if let presentedViewController = vc?.presentedViewController {
          return topViewController(presentedViewController)
        }
        return vc
      }
    }
    
    struct ActivityView: View {
        var body: some View {
          Button(action: {
            self.shareApp()
          }) {
            Text("Share")
          }
        }
    }
    
    extension ActivityView {
      func shareApp() {
        let textToShare = "something..."
        let activityViewController = UIActivityViewController(activityItems: [textToShare], applicationActivities: nil)
        
        let viewController = Coordinator.topViewController()
        activityViewController.popoverPresentationController?.sourceView = viewController?.view
        viewController?.present(activityViewController, animated: true, completion: nil)
      }
    }
    
    struct ActivityView_Previews: PreviewProvider {
        static var previews: some View {
            ActivityView()
        }
    }
    

    And this is a preview:

    Hoping to help someone!

提交回复
热议问题