如何在与iOS Swift中的UIActivityViewController共享的WhatsApp中设置不同的参数?

时间:2018-06-25 11:16:45

标签: ios swift share uiactivityviewcontroller

我正在使用UIActivityViewController共享应用程序中的内容。

我想与不同的共享应用程序共享不同的内容。

类似于消息输出。image + text + URL

在Whatsapp中,我想分享下图text + URL

我该怎么做?为此,请参见下面的屏幕截图。

1 个答案:

答案 0 :(得分:2)

我花了很多时间弄清楚了这一点,但这就是它的工作方式:

分两个步骤考虑这个问题:首先,我们需要告诉UIActivityViewController我们要共享哪些内容。其次,我们需要根据每个社交媒体(链接,图像或文本)返回内容。它由社交媒体应用程序决定可以处理哪些内容,并且只有在我们共享正确类型的内容时才会显示。

第一步,我们将尝试愚弄社交媒体应用程序,说我们要共享一个UIImage和一个NSObject。这将打开大多数社交媒体应用程序以进行共享。

第二步,我们将确定用户单击了哪个社交媒体应用,并为其返回适当的内容。

实施:

创建两个UIActivityItemSource,一个将返回UIImage,另一个将返回NSObject。

class SocialActivityItem: NSObject, UIActivityItemSource {
    var img: UIImage?
    var url: URL?

    convenience init(img: UIImage, url: URL) {
        self.init()
        self.img = img
        self.url = url
    }

    // This will be called BEFORE showing the user the apps to share (first step)
    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return img!
    }

    // This will be called AFTER the user has selected an app to share (second step)
    func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType?) -> Any? {
        //Instagram
        if activityType?.rawValue == "com.burbn.instagram.shareextension" {
            return img!
        } else {
            return url
        }
    }
}

class TextActivityItem: NSObject, UIActivityItemSource {
    var textToShare: String?

    convenience init(textToShare: String) {
        self.init()
        self.textToShare = textToShare
    }

    // This will be called BEFORE showing the user the apps to share (first step)
    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return NSObject()
    }

    // This will be called AFTER the user has selected an app to share (second step)
    func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivityType?) -> Any? {
      var text = ""
      if activityType?.rawValue == "net.whatsapp.WhatsApp.ShareExtension" {
          text = "Sharing on Whatsapp"
      }

      if activityType == UIActivityType.postToFacebook {
          text = "Sharing on Facebook"
      }
      return text
    }
}

然后,您只需要设置所有内容:

let url = URL(string: "www.google.com")!
let socialProvider = SocialActivityItem(img: img, url: url)
let textProvider = TextActivityItem(textToShare: "Sharing on social media!")
let activityViewController = UIActivityViewController(activityItems: [socialProvider, textProvider], applicationActivities: nil)