Как реализовать кнопку "share" в Swift

Это какой-то мир кода для твиттера... Я хочу знать, как получить представление действия с акциями, как мы получаем в приложении iOS stack photos...

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

}

Ответ 1

   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)

Ответ 2

Вот как я реализовал обмен с Swift 3, используя правую кнопку на контроллере навигации. Он включает в себя изображение, текст и ссылку.

SWIFT 3

On ViewDidLoad

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

Создать функцию

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

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

SWIFT 4

On 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 для совместного использования ссылки и сообщения с любым приложением, которое их примет.

Ответ 4

подробности

  • Xcode 9.1, Swift 4
  • Xcode 10.2.1 (10E1001), Swift 5

Решение

Решение 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
    }
}

extension Hashable {
    func share() {
        let activity = UIActivityViewController(activityItems: [self], applicationActivities: nil)
        UIApplication.topViewController?.present(activity, animated: true, completion: nil)
    }
}

использование

let str = "String"
str.share()

"Data to share".share()
1.share()

Полный образец

Не забудьте добавить код решения здесь (смотрите выше)

import UIKit

class ViewController: UIViewController {

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

        let button = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 40))
        button.setTitle("Button", for: .normal)
        button.addTarget(self, action: #selector(shareButtonTapped), 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() { "Data to share".share() }
    @objc func imageViewTapped() { imageView?.image?.share() }
}

Пример результата

enter image description here enter image description here

Ответ 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)
    }
}

Ответ 6

ОБНОВЛЕНО ДЛЯ SWIFT 3.0

//первая функция, чтобы добавить кнопку в панель навигации

func addingNavBarBtn () {

    // setting button 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 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)

}

Ответ 7

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

Ответ 8

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

Ответ 9

 @IBAction func action_shareOnSocial(_ sender: UIButton) {

    //  Converted to Swift 4 by Swiftify v4.1.6809 - https://objectivec2swift.com/
    let theMessage = "Text you want to set , https://www.hackingwithswift.com/"

    let items = [theMessage]

    // build an activity view controller
    let controller = UIActivityViewController(activityItems: items, applicationActivities: nil)

    let popPresenter: UIPopoverPresentationController? = controller.popoverPresentationController
    popPresenter?.sourceView = sender

    // and present it
    self.presentActivityController(controller)

}

func presentActivityController(_ controller: UIActivityViewController?) {
    // for iPad: make the presentation a Popover
    controller?.modalPresentationStyle = .popover

    if let aController = controller {
        present(aController, animated: true)
    }

    let popController: UIPopoverPresentationController? = controller?.popoverPresentationController

    popController?.permittedArrowDirections = .any

    popController?.barButtonItem = navigationItem.leftBarButtonItem

    // access the completion handler
    controller?.completionWithItemsHandler = { activityType, completed, returnedItems, error in
        // react to the completion
        if completed {

        } else {
            // user cancelled
            print("We didn't want to share anything after all.")
        }
    }
}

Ответ 10

Улучшение в коде JP Aquino для Swift 5 для общего действия rightBarButtonItem на навигационном контроллере.

В viewDidLoad вашего ViewController сделайте это:

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

Затем shareBarButtonItemClicked метод shareBarButtonItemClicked как 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)
}

Удачного кодирования!