iOS share sheets are a great way to allow your users to share content from your app. This is a great way to provide your users with the ability to share your app with their network of friends and family for you. A recommendation from somebody you trust is both more powerful than an advertisement and free for the app owner. It is also very easy to do.

Tutorial

Firstly, add this extension to the UIViewController to your project. It requires you to pass in your object and will present a share sheet for this object on the active UIViewController.


import UIKit
// Extension
extension UIViewController {
func presentShareSheet(for object: Object) {
guard let text = object.text,
let image = object.image,
let url = object.url else {
return
}
let activityViewController = UIActivityViewController(activityItems: [text, image, url], applicationActivities: [])
viewController.present(activityViewController, animated: true, completion: nil)
}
}

Next, we have the implementation, we want to create an object with three parameters (text, image, and url), then we call our presentShareSheet function from our extension.


import UIKit
class ShareSheetViewController: UIViewController {
@IBOutlet var exampleLabel: UILabel!
@IBOutlet var exampleImageView: UIImageView!
let exampleURL = URL(string: "https://ios-cookbook.com/")
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: IBAction Methods
@IBAction func present(sender: Any?) {
let object: Object = Object(text: exampleLabel.text, image: exampleImageView.image, url: exampleURL)
presentShareSheet(for: object)
}
}

As you can see we are doing this inside an IBAction, so we can create the share sheet whenever we like. And something like the image below is what you should see.

 

The full source code for a test project I have created for displaying iOS share sheets is available:

https://github.com/rtking1993/ShareSheet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.