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


130

我想知道如何与iOS中的其他应用共享,从而开始了我的搜索工作。我发现两种重要的方法是

  • UIActivityViewController
  • UIDocumentInteractionController

这些方法和其他方法在此SO答案中进行比较。

通常,当我学习一个新概念时,我喜欢看一个入门的基本示例。一旦完成基本设置,以后就可以修改它了。

有许多与相关的问题UIActivityViewController,但我找不到任何仅要求一个简单示例的问题。由于我刚刚学习了如何执行此操作,因此我将在下面提供自己的答案。随时添加一个更好的版本(或Objective-C版本)。

Answers:


278

UIActivityViewController示例项目

用两个按钮设置情节提要,然后将其连接到视图控制器(请参见下面的代码)。

在此处输入图片说明

将图像添加到Assets.xcassets。我称我为“狮子”。

在此处输入图片说明

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 = [ UIActivityType.airDrop, UIActivityType.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 = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]

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

}

结果

单击“共享一些文本”在左侧提供结果,然后单击“共享图像”在右侧提供结果。

在此处输入图片说明

笔记

  • 我在iOS 11和Swift 4上进行了重新测试。由于超时,我不得不在模拟器中运行了几次。这可能是因为我的计算机运行缓慢。
  • 如果您希望隐藏其中的一些选择,则可以使用excludedActivityTypes上面的代码中所示的方法。
  • popoverPresentationController?.sourceView在iPad上运行时,不包括该行将导致您的应用程序崩溃。
  • 这不允许您与其他应用程序共享文本或图像。您可能想要UIDocumentInteractionController

也可以看看


1
为什么有些示例显示1个项目的数组,而有些显示2个?假设共享图像。
Lim Thye Chean

@ Suragch:嗨,我想在文本中共享一个引荐代码,并需要在单击或点击时复制该代码,因为我们在发送号码时会发生这种情况。
Ishika '18

73

分享:文字

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

分享:文字-图片-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)
   }

在此处输入图片说明


4
嘿,它不起作用。在FB中,仅链接不共享图像和文本。
Ekta Padaliya

@ScriptKitty。消息应用是否已使用i Cloud帐户正确配置?
阿怀斯·法亚兹

1
@EktaPadaliya。根据FB更新策略,可以共享URL或图像。文字不能
AWAIS Fayyaz


2
在WhatsApp中未共享@ Mr.JavedMultani图像
NickCoder

10

如果您想共享整个屏幕,我发现它可以完美地工作。

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

9

请注意,您也可以将其用于iPad:

activityViewController.popoverPresentationController?.sourceView = sender

因此,弹出窗口会从发送方弹出(在这种情况下为按钮)。


activityViewController.popoverPresentationController?.sourceView =发件人为?UIView-为我工作。:)谢谢
Brian

iPad上没有出现“共享”框。这解决了我遇到的iPad问题!
Asp上传

3

您可以使用我在项目的一个帮助器类中编写的以下函数。

只是打电话

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

完美的作品!👍🏻
Ravindra_Bhati

3

我使用了上面的实现,现在我才知道它在运行iOS 13的iPad上不起作用。为了使它正常工作,我不得不在present()调用之前添加这些行。

//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)
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.