ios 如何在 Swift 中实现“分享按钮”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37938722/
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 09:29:08  来源:igfitidea点击:

How to implement "share button" in Swift

iosswiftsocial-networking

提问by Santosh

This the some peace of code for twitter ... I want to know how to get the share action view like we get in ios stack photos app...

这是 twitter 代码的一些和平......我想知道如何像我们在 ios 堆栈照片应用程序中一样获得共享操作视图......

@IBAction func twitterButton(sender: AnyObject) {

        let image: UIImage = UIImage(named: "LaunchScreenImage.png")!

        let twitterControl = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
        twitterControl.setInitialText("")
        twitterControl.addImage(image)

        let completionHandler = {(result:SLComposeViewControllerResult) -> () in
            twitterControl.dismissViewControllerAnimated(true, completion: nil)
            switch(result){
            case SLComposeViewControllerResult.Cancelled:
                print("User canceled", terminator: "")
            case SLComposeViewControllerResult.Done:
                print("User tweeted", terminator: "")
            }
    }
        twitterControl.completionHandler = completionHandler
        self.presentViewController(twitterControl, animated: true, completion: nil)

}

回答by Santosh

let firstActivityItem = "Text you want"
let secondActivityItem : NSURL = NSURL(string: "http//:urlyouwant")!
// If you want to put an image
let image : UIImage = UIImage(named: "image.jpg")!

let activityViewController : UIActivityViewController = UIActivityViewController(
    activityItems: [firstActivityItem, secondActivityItem, image], applicationActivities: nil)

// This lines is for the popover you need to show in iPad 
activityViewController.popoverPresentationController?.sourceView = (sender as! UIButton)

// This line remove the arrow of the popover to show in iPad
activityViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.allZeros
activityViewController.popoverPresentationController?.sourceRect = CGRect(x: 150, y: 150, width: 0, height: 0)

// Anything you want to exclude
activityViewController.excludedActivityTypes = [
    UIActivityTypePostToWeibo,
    UIActivityTypePrint,
    UIActivityTypeAssignToContact,
    UIActivityTypeSaveToCameraRoll,
    UIActivityTypeAddToReadingList,
    UIActivityTypePostToFlickr,
    UIActivityTypePostToVimeo,
    UIActivityTypePostToTencentWeibo
]

self.presentViewController(activityViewController, animated: true, completion: nil)

回答by JP Aquino

This is how I implemented sharing with Swift 4/5 using a right button on the Navigation Controller. It includes an image, text and link.

这就是我使用导航控制器上的右键实现与 Swift 4/5 共享的方式。它包括图像、文本和链接。

SWIFT 4/5

快速 4/5

On ViewDidLoad

在 ViewDidLoad 上

 navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Share", style: .plain, target: self, action: #selector(share(sender:)))

Create the function

创建函数

 @objc func share(sender:UIView){
        UIGraphicsBeginImageContext(view.frame.size)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        let textToShare = "Check out my app"

        if let myWebsite = URL(string: "http://itunes.apple.com/app/idXXXXXXXXX") {//Enter link to your app here
            let objectsToShare = [textToShare, myWebsite, image ?? #imageLiteral(resourceName: "app-logo")] as [Any]
            let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)

            //Excluded Activities
            activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, UIActivity.ActivityType.addToReadingList]
            //

            activityVC.popoverPresentationController?.sourceView = sender
            self.present(activityVC, animated: true, completion: nil)
        }    }

回答by onemillion

  @IBAction func shareButtonClicked(sender: AnyObject)
    {
        //Set the default sharing message.
        let message = "Message goes here."
        //Set the link to share.
        if let link = NSURL(string: "http://yoururl.com")
        {
            let objectsToShare = [message,link]
            let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
            activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList]
            self.presentViewController(activityVC, animated: true, completion: nil)
        }
    }

This will allow you to present a UIActivityViewController to share a link and a message with any application that will accept them.

这将允许您呈现一个 UIActivityViewController 以与将接受它们的任何应用程序共享链接和消息。

回答by Vasily Bodnarchuk

Details

细节

  • Xcode 11.4.1 (11E503a), Swift 5.2
  • Xcode 11.4.1 (11E503a),Swift 5.2

Solution

解决方案

TopViewControllersolution

TopViewController解决方案

extension UIApplication {
    class var topViewController: UIViewController? { return getTopViewController() }
    private class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController { return getTopViewController(base: nav.visibleViewController) }
        if let tab = base as? UITabBarController {
            if let selected = tab.selectedViewController { return getTopViewController(base: selected) }
        }
        if let presented = base?.presentedViewController { return getTopViewController(base: presented) }
        return base
    }

    private class func _share(_ data: [Any],
                              applicationActivities: [UIActivity]?,
                              setupViewControllerCompletion: ((UIActivityViewController) -> Void)?) {
        let activityViewController = UIActivityViewController(activityItems: data, applicationActivities: nil)
        setupViewControllerCompletion?(activityViewController)
        UIApplication.topViewController?.present(activityViewController, animated: true, completion: nil)
    }

    class func share(_ data: Any...,
                     applicationActivities: [UIActivity]? = nil,
                     setupViewControllerCompletion: ((UIActivityViewController) -> Void)? = nil) {
        _share(data, applicationActivities: applicationActivities, setupViewControllerCompletion: setupViewControllerCompletion)
    }
    class func share(_ data: [Any],
                     applicationActivities: [UIActivity]? = nil,
                     setupViewControllerCompletion: ((UIActivityViewController) -> Void)? = nil) {
        _share(data, applicationActivities: applicationActivities, setupViewControllerCompletion: setupViewControllerCompletion)
    }
}

Usage

用法

UIApplication.share("Text to share")

let data = ["Text, Image and url", image, url] as [Any]
UIApplication.share(data)

Full sample

完整样品

Do not forget to add the solution code here(look above)

不要忘记在此处添加解决方案代码(见上)

import UIKit

class ViewController: UIViewController {

    private weak var imageView: UIImageView?
    override func viewDidLoad() {
        super.viewDidLoad()

        var button = UIButton(frame: CGRect(x: 50, y: 50, width: 200, height: 40))
        button.setTitle("Share text", for: .normal)
        button.addTarget(self, action: #selector(shareButtonTapped), for: .touchUpInside)
        button.setTitleColor(.blue, for: .normal)
        view.addSubview(button)

        button = UIButton(frame: CGRect(x: 50, y: 80, width: 200, height: 40))
        button.setTitle("Share text & image", for: .normal)
        button.addTarget(self, action: #selector(shareCombinedData), for: .touchUpInside)
        button.setTitleColor(.blue, for: .normal)
        view.addSubview(button)

        let imageView = UIImageView(frame: CGRect(x: 50, y: 120, width: 200, height: 200))
        imageView.image = UIImage(named: "image")
        imageView.isUserInteractionEnabled = true
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageViewTapped)))
        view.addSubview(imageView)
        self.imageView = imageView

    }

    @objc func shareButtonTapped() { UIApplication.share("Text to share") }
    @objc func imageViewTapped() {
        guard let image = imageView?.image else { return }
        UIApplication.share(image)
    }
    @objc func shareCombinedData() {
        guard let image = imageView?.image, let url = URL(string: "http://google.com") else { return }
        let data = ["Text, Image and url", image, url] as [Any]
        UIApplication.share(data)
    }
}

Sample result

示例结果

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

回答by Celil Bozkurt

I develop @onemillion 's answer:) You can use this for Swift 3

我开发了@onemillion 的答案:) 您可以将它用于Swift 3

override func viewDidLoad() {
    super.viewDidLoad()

    share(message: "selam", link: "htttp://google.com")
}

func share(message: String, link: String) {
    if let link = NSURL(string: link) {
        let objectsToShare = [message,link] as [Any]
        let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
        self.present(activityVC, animated: true, completion: nil)
    }
}

回答by MhmdRizk

UPDATED FOR SWIFT 3.0

为 Swift 3.0 更新

// first function to add the button to your navigation bar

// 将按钮添加到导航栏的第一个函数

func addingNavBarBtn () {

    // setting button's image

    let comunicateImage = UIImage(named: "NavfShare")

    let comunicateBtn = UIBarButtonItem(image: comunicateImage, style: .plain, target: self, action: #selector(shareButtonPressed))

    comunicateBtn.tintColor = UIColor.white

    self.navigationItem.rightBarButtonItem = comunicateBtn

}

//setting button's action

func shareButtonPressed(){

    //checking the object and the link you want to share


    let urlString = "https://www.google.com"



    let linkToShare = [urlString!]

    let activityController = UIActivityViewController(activityItems: linkToShare, applicationActivities: nil)

    self.present(activityController, animated: true, completion: nil)

}

回答by Vick Swift

Improving on JP Aquino'scode for Swift 5for share action rightBarButtonItem on the Navigation Controller.

改进JP Aquino 的代码,Swift 5用于在导航控制器上共享操作 rightBarButtonItem。

In viewDidLoadof your ViewController, do this:

viewDidLoad您的 ViewController 中,执行以下操作:

 navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareBarButtonItemClicked(_:)))

Then implement the shareBarButtonItemClickedmethod as below somewhere inside your ViewController:

然后shareBarButtonItemClicked在您的 ViewController 中的某处实现如下方法:

  @objc func shareBarButtonItemClicked(_ sender: UIBarButtonItem) {
    // Text to share with other apps
    let textToShare = String(describing: "My awesome app")
    // URL, and or, and image to share with other apps
    guard let myAppURLToShare = URL(string: "http://itunes.apple.com/app/idXXXXXXXXX"), let image = UIImage(named: "image.jpg") else {
        return
    }
    let items = [textToShare, myAppURLToShare, image] as [Any]
    let avc = UIActivityViewController(activityItems: items, applicationActivities: nil)

    //Apps to exclude sharing to
    avc.excludedActivityTypes = [
        UIActivityType.airDrop,
        UIActivityType.print,
        UIActivityType.saveToCameraRoll,
        UIActivityType.addToReadingList
    ]
    //If user on iPad
    if UIDevice.current.userInterfaceIdiom == .pad {
        if avc.responds(to: #selector(getter: UIViewController.popoverPresentationController)) {
            avc.popoverPresentationController?.barButtonItem = sender
        }
    }
    //Present the shareView on iPhone
    self.present(avc, animated: true, completion: nil)
}

Happy coding!

快乐编码!

回答by Dian

@IBAction func shareButtonAction(_ sender: AnyObject) {   

let activityVC = UIActivityViewController(activityItems: ["Whatever you    want to share"], applicationActivities: nil)
    activityVC.popoverPresentationController?.sourceView = self.view
    present(activityVC, animated: true, completion: nil)
    activityVC.completionWithItemsHandler = { (activityType, completed:Bool, returnedItems:[Any]?, error: Error?) in

        if completed  {
            self.dismiss(animated: true, completion: nil)
        }
    }
}

回答by Amul4608

let items = ["Your Sharing Content"];
let activity = UIActivityViewController(activityItems: items, applicationActivities: nil);
self.present(activity, animated: true, completion: nil)

回答by Shakeel Ahmed

Swift 5

斯威夫特 5

In this regrad pray for me friends

在这个regrad为我祈祷朋友

@IBAction func sharePressed(_ sender: Any) {
    guard let _ = tempImageView.image else {
      return
    }
    if pathGif == nil {
      return
    }
    let shareURL: NSURL = pathGif! as NSURL
    let shareData: NSData = NSData(contentsOf: shareURL as URL)!
    let gifData:  [Any] = [shareData as Any]

    let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: gifData, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view
    activityViewController.excludedActivityTypes = [
       UIActivity.ActivityType.postToWeibo,
       UIActivity.ActivityType.print,
       UIActivity.ActivityType.assignToContact,
       UIActivity.ActivityType.saveToCameraRoll,
       UIActivity.ActivityType.addToReadingList,
       UIActivity.ActivityType.postToFlickr,
       UIActivity.ActivityType.postToVimeo,
       UIActivity.ActivityType.postToTencentWeibo
    ]
    self.present(activityViewController, animated: true, completion: nil)
}