Topics

#71: UIActivityViewController Basics 🌼

Topics

UIActivityViewController is one of the main ways we can allow our apps to talk with each other, as well as allow our users to share content with the world. Let's take a look. UIActivityViewController accepts an array of activityItems which can be of many types:

let shareText = "#71: UIActivityViewController Basics"
let shareURL = NSURL(string: "https://littlebitesofcocoa.com/71")!
let shareImage = UIImage(named: "71-thumbnail")!

let itemsToShare = [shareText, shareURL, shareImage]

let activityVC = UIActivityViewController(
  activityItems: itemsToShare, applicationActivities: nil
)

presentViewController(activityVC, animated: true, completion: nil)

The activity view controller will intelligently use each item. For example: On Twitter, the text will become the text of a tweet. The URL and image will be appended and shared natively as an image attached to the tweet.

UIActivityViewController is pretty clever. For example, it's smart enough to know if the NSURL we hand it is to a video in the user's Photos library. In such a case, it responds by letting the user share the video with services like Vimeo. We can also pass in an NSData containing the actual video.

We can even allow printing our content by wrapping it in a UISimpleTextPrintFormatter and passing that in:

let printData = UISimpleTextPrintFormatter(text: biteContent)
let itemsToShare = [biteTitle, printData]

Finally, we can use the completeWithItemsHandler closure to learn if the user actually performed a share or action in our activity view controller, as well as what specific activity they chose.

activityVC.completionWithItemsHandler = {
  (activityType, completed, items, error) in

  guard completed else { print("User cancelled."); return }

  print("Completed With Activity Type: \(activityType)")

  if activityType == UIActivityTypePostToFacebook {
    print("Shared on Facebook")
  }
}