用 Swift 中的 UIActivityViewController 共享文本或图像的基本示例

我开始搜索是想知道如何与 iOS 中的其他应用程序分享。我发现两个重要的方法是

  • UIActivityViewController
  • UIDocumentInteractionController

这些方法和其他方法在 这么回答中进行了比较。

通常当我学习一个新概念时,我喜欢看一个基本的例子来开始。一旦我得到一些基本的设置,我可以修改它如何我喜欢以后。

有许多关于 UIActivityViewController的 SO 问题,但是我找不到任何仅仅是要求一个简单的例子的问题。由于我刚刚学会如何做到这一点,我将在下面提供我自己的答案。请随意添加一个更好的版本(或 Objective-C 版本)。

198055 次浏览

UIActivityViewController 示例项目

用两个按钮设置你的故事板,并将它们连接到你的视图控制器(见下面的代码)。

enter image description here

给你的 Assets.xcassets 添加一个图片,我把我的叫做“狮子”。

enter image description here

密码

import UIKit
class ViewController: UIViewController {
    

// share text
@IBAction func shareTextButton(_ sender: UIButton) {
        

// text to share
let text = "This is some text that I want to share."
        

// set up activity view controller
let textToShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
        

// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivity.ActivityType.airDrop, UIActivity.ActivityType.postToFacebook ]
        

// present the view controller
self.present(activityViewController, animated: true, completion: nil)
        

}
    

// share image
@IBAction func shareImageButton(_ sender: UIButton) {
        

// image to share
let image = UIImage(named: "Image")
        

// set up activity view controller
let imageToShare = [ image! ]
let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
        

// exclude some activity types from the list (optional)
activityViewController.excludedActivityTypes = [ UIActivity.ActivityType.airDrop, UIActivity.ActivityType.postToFacebook ]
        

// present the view controller
self.present(activityViewController, animated: true, completion: nil)
}
    

}

结果

单击“ Share some text”在左侧显示结果,单击“ Share an image”在右侧显示结果。

enter image description here

笔记

  • 我用 iOS11和 Swift 4重新测试了一下。我不得不在模拟器里运行了几次,因为它超时了。这可能是因为我的电脑速度太慢。
  • 如果您希望隐藏其中的一些选择,可以使用 excludedActivityTypes来实现,如上面的代码所示。
  • 不包括 popoverPresentationController?.sourceView线将导致你的应用程序崩溃时,运行在 iPad 上。
  • 这不允许您共享文本或图像到其他应用程序。您可能需要 UIDocumentInteractionController为此。

参见

作为一个注意事项,你也可以把它用在 iPad 上:

activityViewController.popoverPresentationController?.sourceView = sender

所以弹出窗口将从发送方弹出(在这种情况下是按钮)。

如果你想分享整个屏幕,我发现这个工作完美无缺。

@IBAction func shareButton(_ sender: Any) {


let bounds = UIScreen.main.bounds
UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
self.view.drawHierarchy(in: bounds, afterScreenUpdates: false)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let activityViewController = UIActivityViewController(activityItems: [img!], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}

您可以使用以下函数,这些函数是我在项目中的助手类中编写的。

打电话吧

showShareActivity(msg:"message", image: nil, url: nil, sourceRect: nil)

它同时适用于 iPhone 和 iPad。如果你通过 sourceRect 传递任何视图的 CGRect 值,它也会在 iPad 中显示一个小箭头。

func topViewController()-> UIViewController{
var topViewController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!


while ((topViewController.presentedViewController) != nil) {
topViewController = topViewController.presentedViewController!;
}


return topViewController
}


func showShareActivity(msg:String?, image:UIImage?, url:String?, sourceRect:CGRect?){
var objectsToShare = [AnyObject]()


if let url = url {
objectsToShare = [url as AnyObject]
}


if let image = image {
objectsToShare = [image as AnyObject]
}


if let msg = msg {
objectsToShare = [msg as AnyObject]
}


let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityVC.modalPresentationStyle = .popover
activityVC.popoverPresentationController?.sourceView = topViewController().view
if let sourceRect = sourceRect {
activityVC.popoverPresentationController?.sourceRect = sourceRect
}


topViewController().present(activityVC, animated: true, completion: nil)
}

分享: 文本

@IBAction func shareOnlyText(_ sender: UIButton) {
let text = "This is the text....."
let textShare = [ text ]
let activityViewController = UIActivityViewController(activityItems: textShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
}

图片分享:

@IBAction func shareOnlyImage(_ sender: UIButton) {
let image = UIImage(named: "Product")
let imageShare = [ image! ]
let activityViewController = UIActivityViewController(activityItems: imageShare , applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}

分享: Text-Image-URL

   @IBAction func shareAll(_ sender: UIButton) {
let text = "This is the text...."
let image = UIImage(named: "Product")
let myWebsite = NSURL(string:"https://stackoverflow.com/users/4600136/mr-javed-multani?tab=profile")
let shareAll= [text , image! , myWebsite]
let activityViewController = UIActivityViewController(activityItems: shareAll, applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}

enter image description here

我已经使用了上面的实现,现在我知道它不能在运行 iOS13的 iPad 上工作。 为了使其正常工作,我必须在现在()调用之前添加这些代码行

//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
popoverController.sourceView = self.view
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}

对我来说就是这样

func shareData(_ dataToShare: [Any]){


let activityViewController = UIActivityViewController(activityItems: dataToShare, applicationActivities: nil)


//exclude some activity types from the list (optional)
//activityViewController.excludedActivityTypes = [
//UIActivity.ActivityType.postToFacebook
//]


//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
popoverController.sourceView = self.view
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}


self.present(activityViewController, animated: true, completion: nil)
}