Blog

How to share images from an iOS app in Instagram Stories, WhatsApp and Facebook

In this tutorial, you’ll learn, how to share images, text (or even UIView) from your iOS application on popular social media platforms and services by using Swift.

Preparing images is quite easy, although, in the case of Facebook, you’ll need a special client ID. So, without further ado, let the fun begin!

Table of content

  1. Preparing UIImage for sharing
  2. Passing images to Instagram Stories
  3. Passing an image to WhatsApp
  4. Passing an image to Facebook
  5. Preparing UIImage for sharing

    The first thing is to prepare UIImage for sharing.

    In many cases, you’ll have a ready image. Be it from API, hardcoded in your iOS application, or somewhere else.

    But in other cases, you’ll need to prepare an image from the view displayed in the application.

    Let’s say, we have a controller that shows images, labels, buttons, etc.

    We want to pass it to Facebook or WhatsApp. To do this, we need to prepare UIImage from UIView, then change it to Data and pass it to other social media apps.

    Let’s start with embedding the prepared views into one UIView.

    It can be UIController’s view, but if we don’t want to get navigation elements, we should use another approach. In that case, we should embed our views inside one view. It can be a simple UIView, UIStackView, UITableView, etc.

    For example:

    let topImageVIew = UIImageView()
    let titleLabel = UILabel()
    let bottomButton = UIButton()
    

    We can create a basic container view and embed other views as subviews:

    let containerView = UIView()
    containerView.addSubview(topImageVIew)
    containerView.addSubview(titleLabel)
    containerView.addSubview(bottomButton)
    

    OK, now we have one view that contains other views and can be converted into UIImage.

    Let’s prepare a solution that will help us with this task. The simplest option is to add an extension for UIView(). It will look like this:

    extension UIView {
       func asImage() -> UIImage {
           let renderer = UIGraphicsImageRenderer(bounds: bounds)
           return renderer.image { rendererContext in
               layer.render(in: rendererContext.cgContext)
           }
       }
    }
    

    This extension will transform UIView that we’ve just created into UIImage. The UIImage can be used for sharing on social media apps.

    So when we call it, we’ll get an image:

    let myImage = containerView.asImage()

    How to share an image on Instagram from iOS Swift

    Sharing images from an iOS application on Instagram Stories isn’t difficult.

    We’ll need just one method that will pass data to a specific app. Of course, it’s good to check, if Instagram is installed on the user’s iPhone. But the whole function will look like this:

       func shareToInstagramStories(image: UIImage, urlScheme: URL) {
           guard let imageData: Data = image.pngData() else { return }
           let items = [["com.instagram.sharedSticker.backgroundImage": imageData]]
           let pasteboardOptions = [UIPasteboard.OptionsKey.expirationDate: Date().addingTimeInterval(60*5)]
           UIPasteboard.general.setItems(items, options: pasteboardOptions)
           UIApplication.shared.open(urlScheme, options: [:], completionHandler: nil)
       }
    

    Image is our view transformed into UIImage and urlScheme is URL made on the "instagram-stories://share" String.

    To check if Instagram Stories is on the user’s phone, and pass the data, we need to add LSApplicationQueriesSchemes to the .plist file. The same we’ll need to do for adding WhatsApp or Facebook share options.

    How to share an image on WhatsApp from iOS Swift

    Now, let’s check, how sharing from iOS apps for WhatsApp works.

    It’s almost the same as in the previous example:

       func shareToWhatsApp(image: UIImage, view: UIView, urlScheme: URL) {
           guard let imageData = image.pngData() else { return }
           let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
           try? imageData.write(to: tempFile, options: .atomicWrite)
           documentInteractionController = UIDocumentInteractionController(url: tempFile)
           documentInteractionController?.uti = "net.whatsapp.image"
           documentInteractionController?.presentOpenInMenu(from: .zero, in: view, animated: true)
       }
    

    The URL scheme in this case will be "whatsapp://app”.

    When we have it, we can move on to Facebook.

    How to share an image on Facebook from iOS Swift

    Let’s check the method for sharing images on Facebook and what it will look like.

       func shareToFacebook(image: UIImage, urlScheme: URL, appId: String) {
           guard let imageData: Data = image.pngData() else { return }
           let items = [["com.facebook.sharedSticker.backgroundImage": imageData,
                         "com.facebook.sharedSticker.appID": appId]]
           let pasteboardOptions = [UIPasteboard.OptionsKey.expirationDate: Date().addingTimeInterval(60*5)]
           UIPasteboard.general.setItems(items, options: pasteboardOptions)
           UIApplication.shared.open(urlScheme, options: [:], completionHandler: nil)
       }
    

    As you can see, besides ImageData, there is also appID.

    The Facebook developer documentation says that appID is required as your Facebook app ID. You can get it from your account.

    The appID should be added to the Info.plist file. Unless you add it, sharing won’t be working properly. Same as with WhatsApp or Instagram Stories, the urlScheme is needed for Facebook sharing.

    It looks like this:

    "facebook-stories://share”.

    And that's pretty much all you need to know about sharing images on Facebook, WhatsApp and Instagram using iOS Swift. Until next time!!

Check our latest product - it's based on our experience of managing over 50-people strong company. The tool we're missing as a small company and not an enterprise.

humadroid.io is an employee and performance management software. It's an unique tool allowing everyone to be in the loop - by having up to date info about co-workers, time-off, benefits, assets, helping with one-on-ones, being a go-to place for company-wide announcements.

Check out humadroid.io
Top

Contact us

* Required fields

The controller of your personal data provided via this contact form is Prograils sp. z o.o., with a registered seat at Sczanieckiej 9A/10, 60-215 Poznań. Your personal data will be processed in order to respond to your inquiries and for our marketing purposes (e.g. when you ask us for our post-development, maintenance or ad hoc engagements for your app). You have the rights to: access your personal data, rectify or erase your personal data, restrict the processing of your personal data, data portability and to object to the processing of your personal data. Learn more.

Notice

We do not track you online. We use only session cookies and anonymous identifiers for the purposes specified in the cookie policy. No third-party trackers.

I understand
Elo Mordo!Elo Mordo!