9
votes

Sharing a image from UIImageView using UIActivityViewController?

I am trying to share a image using UIActivityViewController, but I get error:

func shareIMG(){
    let activityItems = [self.imageView.image]
    let avc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)

    self.presentViewController(avc, animated: true, completion: nil)
}

Error message:

Cannot find an initializer for type 'UIActivityViewController' that accepts an argument list of type '(activityItems: [UIImage?], applicationActivities: nil)'

Any ideas?

4

4 Answers

17
votes
let activityItem: [AnyObject] = [self.imageView.image as! AnyObject]

let avc = UIActivityViewController(activityItems: activityItem as [AnyObject], applicationActivities: nil)

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

Note : The above code tested in Xcode 6.3 simulator

5
votes

Just create a button and it's action. And install the button's action like this.

Note: You have to log in your facebook or twitter by going to setting. Then do like this.

@IBAction func onShareTouched(sender: AnyObject) {

    print("share")

    let myShare = "My beautiful photo! <3 <3"
    let image: UIImage = UIImage(named: "yourImageNameHere")

    let shareVC: UIActivityViewController = UIActivityViewController(activityItems: [(image), myShare], applicationActivities: nil)
    self.presentViewController(shareVC, animated: true, completion: nil)

}
2
votes

Full code working for iPhones and iPads for Swift:

func share(sender: UIButton){
    let img: UIImage = UIImage(named: "lenna")!
    let messageStr:String  = "some sharing text"
    let shareItems:Array = [img, messageStr]

    activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
    activityViewController!.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypePostToWeibo, UIActivityTypeCopyToPasteboard, UIActivityTypeAddToReadingList, UIActivityTypePostToVimeo]

    if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone {
        self.presentViewController(activityViewController!, animated: true, completion: nil)
    } else {
        let popup: UIPopoverController = UIPopoverController(contentViewController: activityViewController!)
        popup.presentPopoverFromRect(sender.bounds, inView: sender, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
    }
}
0
votes

It looks like you need to unwrap activityItems with a !