UIActivityViewController in Swift
Just a simple example of using the UIActivityViewController in Swift.
You need to be logged into Facebook and Twitter for the options to share to them shows up. You can do this in the simulator by going to the settings app. If you do not log in, then you will just see Mail and Copy as options.
Set up
All that is needed is to instantiate UIActivityViewController with the item[s] to share, then present it. Here is a simple example:
1 2 3 4 5 6 7 8 9 10 |
let someText:String = textView.text let google:NSURL = NSURL(string:"http://google.com/") // let's add a String and an NSURL let activityViewController = UIActivityViewController( activityItems: [someText, google], applicationActivities: nil) self.navigationController.presentViewController(activityViewController, animated: true, completion: nil) |
You can specify that there are sharing options that you do not want like this. This is all of them, so in real life you wouldn’t want to exclude them all.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
activityViewController.excludedActivityTypes = [ UIActivityTypePostToTwitter, UIActivityTypePostToFacebook, UIActivityTypePostToWeibo, UIActivityTypeMessage, UIActivityTypeMail, UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll, UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo ] |
If you want to do something upon completion, install a handler like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
activityViewController.completionHandler = {(activityType, completed:Bool) in if !completed { println("cancelled") return } if activityType == UIActivityTypePostToTwitter { println("twitter") } if activityType == UIActivityTypeMail { println("mail") } } |
Download the project from this Github repository.