web-dev-qa-db-fra.com

Comment implémenter le "bouton de partage" dans Swift

C'est la paix du code pour Twitter ... Je veux savoir comment obtenir la vue d'action de partage, comme nous obtenons dans l'application iOS Photos 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)

}
14
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)
20
Santosh

Voici comment j'ai implémenté le partage avec Swift 3 en utilisant un bouton droit sur le contrôleur de navigation. Il comprend une image, un texte et un lien.

Sur ViewDidLoad

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

Crée la fonction

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)
        }    }
14
JP Aquino

Détails

xCode 9.1, Swift 4

Solution

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

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

Usage

let str = "String"
str.share()

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

Échantillon complet

import UIKit

class ViewController: UIViewController {

    let imageView = UIImageView(frame: CGRect(x: 50, y: 120, width: 200, height: 200))
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        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)

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

    @objc func shareButtonTapped() {
         "Data to share".share()
    }

    @objc func imageViewTapped() {
        imageView.image?.share()
    }
}

Exemple de résultat

 enter image description here  enter image description here

8
Vasily Bodnarchuk
  @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)
        }
    }

Cela vous permettra de présenter un UIActivityViewController pour partager un lien et un message avec toute application qui les acceptera. 

8
onemillion

Je développe la réponse de @onemillion :) Vous pouvez utiliser ceci pour 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)
    }
}
4
Celil Bozkurt

MISE À JOUR POUR Swift 3.0

// première fonction pour ajouter le bouton à votre barre de navigation

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)

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