10

我想知道是否有通过 SwiftUI 导出或共享文件的好方法。似乎没有办法包装 UIActivityViewController 并直接呈现它。我使用 UIViewControllerRepresentable 来包装 UIActivityViewController,如果我将它呈现在 SwiftUI 模态中,它就会崩溃。

我能够创建一个通用的 UIViewController,然后从那里调用一个呈现 UIActivityViewController 的方法,但这是很多包装。

如果我们想使用 SwiftUI 从 Mac 共享,有没有办法包装 NSSharingServicePicker?

无论如何,如果有人有他们如何做到这一点的例子,将不胜感激。

4

5 回答 5

17

您可以在任何地方定义此函数(最好在全局范围内):

@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
}

您可以在按钮操作中或其他任何需要的地方使用此功能:

Button(action: {
    share(items: ["This is some text"])
}) {
    Text("Share")
}
于 2019-12-28T22:02:23.057 回答
5

编辑:删除所有代码和对UIButton.

感谢@Matteo_Pacini 对这个问题的回答,向我们展示了这项技术。与他的回答(和评论)一样,(1)边缘很粗糙,(2)我不确定这是苹果希望我们使用的方式UIViewControllerRepresentable,我真的希望他们提供更好的SwiftUI(“SwiftierUI”?)替代品在未来的测试版中。

我做了很多工作,UIKit因为我希望它在 iPad 上看起来不错,sourceView弹出框需要 a。真正的技巧是显示一个(SwiftUI) ,它在视图层次结构View中获取并从.UIActivityViewControllerpresentUIKit

我的需要是展示一个单一的图像来分享,所以事情就是朝着这个方向发展的。假设您有一个图像,存储为一个@State变量 - 在我的示例中,该图像称为vermont.jpg,是的,为此进行了硬编码。

首先,创建一个UIKit`UIViewController 类型的类来显示共享弹出框:

class ActivityViewController : UIViewController {

    var uiImage:UIImage!

    @objc func shareImage() {
        let vc = UIActivityViewController(activityItems: [uiImage!], applicationActivities: [])
        vc.excludedActivityTypes =  [
            UIActivity.ActivityType.postToWeibo,
            UIActivity.ActivityType.assignToContact,
            UIActivity.ActivityType.addToReadingList,
            UIActivity.ActivityType.postToVimeo,
            UIActivity.ActivityType.postToTencentWeibo
        ]
        present(vc,
                animated: true,
                completion: nil)
        vc.popoverPresentationController?.sourceView = self.view
    }
}

主要的事情是;

  • 你需要一个“包装器”UIViewController才能做到这一点present
  • 您需要var uiImage:UIImage!设置activityItems.

接下来,将其包装成一个UIViewControllerRepresentable

struct SwiftUIActivityViewController : UIViewControllerRepresentable {

    let activityViewController = ActivityViewController()

    func makeUIViewController(context: Context) -> ActivityViewController {
        activityViewController
    }
    func updateUIViewController(_ uiViewController: ActivityViewController, context: Context) {
        //
    }
    func shareImage(uiImage: UIImage) {
        activityViewController.uiImage = uiImage
        activityViewController.shareImage()
    }
}

唯一需要注意的两件事是:

  • 实例化ActivityViewController以将其返回ContentView
  • 创建shareImage(uiImage:UIImage) 来调用它。

最后,您有ContentView

struct ContentView : View {
    let activityViewController = SwiftUIActivityViewController()
    @State var uiImage = UIImage(named: "vermont.jpg")
    var body: some View {
        VStack {
            Button(action: {
                self.activityViewController.shareImage(uiImage: self.uiImage!)
            }) {
                ZStack {
                    Image(systemName:"square.and.arrow.up").renderingMode(.original).font(Font.title.weight(.regular))
                    activityViewController
                }
        }.frame(width: 60, height: 60).border(Color.black, width: 2, cornerRadius: 2)
            Divider()
            Image(uiImage: uiImage!)
        }
    }
}

请注意,有一些硬编码和(呃)强制展开uiImage,以及不必要的@State. 这些是因为我打算使用 `UIImagePickerController next 将它们联系在一起。

这里需要注意的事项:

  • 实例化SwiftUIActivityViewController,并shareImage用作 Button 操作。
  • 用它可以作为按钮显示。不要忘记,甚至 aUIViewControllerRepresentable也只是被认为是 SwiftUI View

将图像的名称更改为您项目中的名称,这应该可以工作。您将获得一个居中的 60x60 按钮,其下方有图片。

于 2019-06-30T21:10:40.060 回答
3

我们可以直接从 View (SwiftUI) 调用 UIActivityViewController 而无需使用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()
    }
}

这是一个预览:

在此处输入图像描述

希望能帮助到某人!

于 2020-07-27T02:24:07.930 回答
2

看看AlanQuatermain -s SwiftUIShareSheetDemo

简而言之,它看起来像这样:

@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
    }
}
于 2020-02-03T10:08:39.017 回答
2

这里的大多数解决方案都忘记在 iPad 上填充共享表。

因此,如果您打算让应用程序不会在此设备上崩溃,您可以在使用的地方使用此方法popoverController并添加您想要activityItems的参数。

import SwiftUI

/// Share button to populate on any SwiftUI view.
///
struct ShareButton: View {

  /// Your items you want to share to the world.
  ///
  let itemsToShare = ["https://itunes.apple.com/app/id1234"]

  var body: some View {
    Button(action: { showShareSheet(with: itemsToShare) }) {
      Image(systemName: "square.and.arrow.up")
        .font(.title2)
        .foregroundColor(.blue)
    }
  }
}

extension View {
  /// Show the classic Apple share sheet on iPhone and iPad.
  ///
  func showShareSheet(with activityItems: [Any]) {
    guard let source = UIApplication.shared.windows.last?.rootViewController else {
      return
    }

    let activityVC = UIActivityViewController(
      activityItems: activityItems,
      applicationActivities: nil)

    if let popoverController = activityVC.popoverPresentationController {
      popoverController.sourceView = source.view
      popoverController.sourceRect = CGRect(x: source.view.bounds.midX,
                                            y: source.view.bounds.midY,
                                            width: .zero, height: .zero)
      popoverController.permittedArrowDirections = []
    }
    source.present(activityVC, animated: true)
  }
}
于 2020-12-20T13:42:32.990 回答