【问题标题】:How to implement "share button" in Swift如何在 Swift 中实现“分享按钮”
【发布时间】:2016-10-22 15:58:10
【问题描述】:

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

}

【问题讨论】:

标签: ios swift share social-networking


【解决方案1】:

斯威夫特 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)

【讨论】:

  • 为了让它在今天(2020 年)正常工作,我不得不将 = (sender as! UIButton) 更改为 = self.view,因为我无法将 UIButton 或 UIBarButton 投射为视图。
  • @podcastfan88 你不需要这样做。 UIPopoverPresentationController 有一个名为 barButtonItem 的属性,专门用于锚定到导航栏按钮。
  • 完成处理程序在哪里?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
      @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 以与任何接受它们的应用程序共享链接和消息。

    【讨论】:

    • 选择whatsapp分享时有效,但选择wechat/facebook分享时无法显示消息。有人能解决这个问题吗?
    【解决方案4】:

    详情

    • Xcode 11.4.1 (11E503a)、Swift 5.2

    解决方案

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

    用法

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

    完整样本

    别忘了在此处添加解决方案代码(见上图)

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

    样本结果

    【讨论】:

    • 很好,但最好构建自己的协议而不是覆盖 Equitable,然后将所需的类型与它一致。您的解决方案可能有点误导。
    • @caffeinum 我没有覆盖任何功能。我只是添加新功能。为什么不呢,你的想法我也很有趣。
    • 不错的实现,但是您将如何共享多个项目,例如文本、图像和 URL 一次?
    【解决方案5】:

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

    【讨论】:

    • 这些例子......在哪个星球上有一个共享单个链接的共享按钮?一个获取当前 URL 的示例怎么样,这有点像这里所有用例的 99%...抱歉不得不对某人咆哮
    【解决方案6】:
    let items = ["Your Sharing Content"];
    let activity = UIActivityViewController(activityItems: items, applicationActivities: nil);
    self.present(activity, animated: true, completion: nil)
    

    【讨论】:

      【解决方案7】:

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

      【讨论】:

      • mainAboutUsObject 是从哪里来的?抱歉不熟悉swift,但是例如在Safari中如何获取当前页面的URL?
      • @AlxVallejo mainAboutUsObject 只是一个 API 调用返回的对象,你可以用任何你必须在 safari 中打开的 URL 替换它
      • 什么 API 调用?您的示例中没有 API 调用。这个 var 在代码中突然出现。它会自动发生吗?这是否意味着它会自动引用您共享的链接?这是这些示例似乎都没有解决的基本内容。
      • @AlxVallejo 不,你不需要知道任何关于 API 调用的事情,这个变量是 url 字符串,这是你需要知道的
      【解决方案8】:

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

      编码愉快!

      【讨论】:

        【解决方案9】:
        @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)
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2012-10-24
          • 2020-11-02
          • 1970-01-01
          • 2012-02-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多