如何在 Swift 中实施 "share button"

How to implement "share button" in Swift

这是 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)

}

Swift 5:

    // Setting description
    let firstActivityItem = "Description you want.."

    // Setting url
    let secondActivityItem : NSURL = NSURL(string: "http://your-url.com/")!
    
    // If you want to use an image
    let image : UIImage = UIImage(named: "your-image-name")!
    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.down
    activityViewController.popoverPresentationController?.sourceRect = CGRect(x: 150, y: 150, width: 0, height: 0)
    
    // Pre-configuring activity items
    activityViewController.activityItemsConfiguration = [
    UIActivity.ActivityType.message
    ] as? UIActivityItemsConfigurationReading
    
    // Anything you want to exclude
    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,
        UIActivity.ActivityType.postToFacebook
    ]
    
    activityViewController.isModalInPresentation = true
    self.present(activityViewController, animated: true, completion: nil)
  @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)
        }
    }

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

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

SWIFT 4/5

在 ViewDidLoad 上

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

创建函数

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

我开发了@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)
    }
}

更新 SWIFT 3.0

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

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)

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

详情

  • Xcode 11.4.1 (11E503a), Swift 5.2

解决方案

TopViewController solution

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

用法

UIApplication.share("Text to share")

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

完整样本

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

示例结果

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

在 ViewController 的 viewDidLoad 中,执​​行此操作:

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

然后在你的 ViewController:

中的某个地方实现 shareBarButtonItemClicked 方法
  @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)
}

编码愉快!

@IBAction func shareButtonAction(_ sender: UIButton) {   

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