ios 在 Swift 中与 UIActivityViewController 共享文本或图像的基本示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35931946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:40:20  来源:igfitidea点击:

Basic example for sharing text or image with UIActivityViewController in Swift

iosswiftuiactivityviewcontroller

提问by Suragch

I started my search by wanting to know how I could share to other apps in iOS. I discovered that two important ways are

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

  • UIActivityViewController
  • UIDocumentInteractionController
  • UIActivityViewController
  • UIDocumentInteractionController

These and other methods are compared in this SO answer.

这个 SO answer中比较了这些方法和其他方法。

Often when I am learning a new concept I like to see a basic example to get me started. Once I get something basic set up I can modify it how I like later.

通常当我学习一个新概念时,我喜欢看一个基本的例子来让我开始。一旦我得到了一些基本的设置,我就可以在以后按照我喜欢的方式修改它。

There are many SO questions related to UIActivityViewController, but I couldn't find any that were just asking for a simple example. Since I just learned how to do this, I will provide my own answer below. Feel free to add a better one (or an Objective-C version).

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

回答by Suragch

UIActivityViewController Example Project

UIActivityViewController 示例项目

Set up your storyboard with two buttons and hook them up to your view controller (see code below).

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

enter image description here

在此处输入图片说明

Add an image to your Assets.xcassets. I called mine "lion".

将图像添加到您的 Assets.xcassets。我叫我的“狮子”。

enter image description here

在此处输入图片说明

Code

代码

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

}

Result

结果

Clicking "Share some text" gives result on the left and clicking "Share an image" gives the result on the right.

单击“共享一些文本”会在左侧给出结果,单击“共享图像”会在右侧给出结果。

enter image description here

在此处输入图片说明

Notes

笔记

  • I retested this with iOS 11 and Swift 4. I had to run it a couple times in the simulator before it worked because it was timing out. This may be because my computer is slow.
  • If you wish to hide some of these choices, you can do that with excludedActivityTypesas shown in the code above.
  • Not including the popoverPresentationController?.sourceViewline will cause your app to crash when run on an iPad.
  • This does not allow you to share text or images to other apps. You probably want UIDocumentInteractionControllerfor that.
  • 我用 iOS 11 和 Swift 4 重新测试了它。我不得不在模拟器中运行它几次,然后它才能工作,因为它超时了。这可能是因为我的电脑很慢。
  • 如果您希望隐藏其中一些选项,您可以excludedActivityTypes按照上面的代码所示进行操作。
  • 不包括该popoverPresentationController?.sourceView行会导致您的应用在 iPad 上运行时崩溃。
  • 这不允许您与其他应用程序共享文本或图像。你可能想要UIDocumentInteractionController那个。

See also

也可以看看

回答by Mr.Javed Multani

Share :Text

分享 :文字

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

Share :Image

分享 :图片

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

Share :Text - Image - URL

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

在此处输入图片说明

回答by Diavel Rider

I found this to work flawlessly if you want to share whole screen.

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

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

回答by Adrien Brecheteau

Just as a note you can also use this for iPads:

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

activityViewController.popoverPresentationController?.sourceView = sender

So the popover pops from the sender (the button in that case).

所以弹出框从发件人(在那种情况下是按钮)弹出。

回答by Mahmud Ahsan

You may use the following functions which I wrote in one of my helper class in a project.

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

just call

打电话

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

and it will work for both iPhone and iPad. If you pass any view's CGRect value by sourceRect it will also shows a little arrow in iPad.

它适用于 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)
}

回答by Bréndal Teixeira

I've used the implementation above and just now I came to know that it doesn't work on iPad running iOS 13. I had to add these lines before present() call in order to make it work

我已经使用了上面的实现,现在我才知道它在运行 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)
}

That's how it works for me

这就是它对我的工作方式

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