How to share an image on Instagram with iOS Swift

Nov 9, 2019 07:33 · 815 words · 4 minute read ios ios13 ios14 swift

Today we’re going to look at how to share an image on Instagram from your iOS app using the Swift programming language. Nothing very complex but just a few gotchas and different documentations to go through. I hope the following lines will help you in the process. We’ll start by looking at the two following concepts:

  • Instagram custom URL schemes
  • iOS Document Interaction API

and then we’ll write some Swift code to share an image on Instagram. Let’s get started!

Instagram Custom URL Schemes

Custom URL Schemes allow for simple interactions with the Instagram API from your iOS application, e.g., open the Instagram app, open the camera, go to a specific user feed on Instagram, etc.

A custom URL scheme has two main components:

  • the scheme itself which references instagram, i.e., instagram://
  • the scheme parameter(s) which specifies the custom action you want to perform, e.g., app, camera, user?username=USERNAME, etc.

To be able to use custom URL schemes from your app, the very first thing you need to do is to add it to your Info.plist file. If you don’t have it already, add a new key named LSApplicationQueriesSchemes of type Array and two new String items of values instagram-stories (for sharing to Instagram stories) and instagram:// (for sharing to Instagram feed). Items keys don’t matter.

You can now start using custom Instagram URL schemes! The simplest one is the one used to open the Instagram app. You can use it to actually just open the Instagram app or to test that the Instagram app is installed on the user’s device.

func shareToInstagramFeed(image: UIImage) {
    guard let instagramUrl = URL(string: "instagram://app") else {
        return
    }

    if UIApplication.shared.canOpenURL(instagramUrl) {
        // share something on Instagram
    } else {
        // Instagram app is not installed or can't be opened, pop up an alert
    }
}

iOS Document Interaction API

The Document Interaction API allows you to interact with documents (images in our example) that are already on the user’s device (you can create the file before opening interactions for it). Let’s try it out!

// NOTE: Assumes that you've added UIDocumentInteractionControllerDelegate to your view controller class

func shareFileUrlOnInstagram(fileUrl: URL) {
    let documentController = UIDocumentInteractionController(url: fileUrl)
    // the UTI is given by Instagram
    documentController.uti = "com.instagram.photo"

    // open the document interaction view to share to Instagram
    documentController.presentOpenInMenu(from: self.view.frame, in: self.view, animated: true)
}

Nothing very fancy here. This opens a sharing menu that allows the user to share an existing image at location fileUrl to her Instagram feed. This solution shows also some other sharing options but you can restrict to Instagram only by using the .igo extension for the file and the UTI com.instagram.exclusivegram.

Sharing the image to Instagram

Instagram has two options for sharing images these days:

  • Instagram Feed
  • Instagram Stories

Let’s have a look first at sharing to the Instagram Feed.

Please note that Instagram doesn’t allow to specify the text caption in your app anymore, so the following code will open a new Instagram window where the user can add the text caption.

func shareToInstagramFeed(image: UIImage) {
    // build the custom URL scheme
    guard let instagramUrl = URL(string: "instagram://app") else {
        return
    }

    // check that Instagram can be opened
    if UIApplication.shared.canOpenURL(instagramUrl) {
        // build the image data from the UIImage
        guard let imageData = UIImageJPEGRepresentation(image, 100) else {
            return
        }

        // build the file URL
        let path = (NSTemporaryDirectory() as NSString).appendingPathComponent("instagram.ig")
        let fileUrl = URL(fileURLWithPath: path)

        // write the image data to the file URL
        do {
            try imageData.write(to: fileUrl, options: .atomic)
        } catch {
            // could not write image data
            return
        }

        // instantiate a new document interaction controller
        // you need to instantiate one document interaction controller per file
        let documentController = UIDocumentInteractionController(url: fileUrl)
        documentController.delegate = self
        // the UTI is given by Instagram
        documentController.uti = "com.instagram.photo"

        // open the document interaction view to share to Instagram feed
        documentController.presentOpenInMenu(from: self.view.frame, in: self.view, animated: true)
    } else {
        // Instagram app is not installed or can't be opened, pop up an alert
    }
}

As you can see, this reuses the two concepts we have discussed above, custom URL schemes and the Document Interaction API.

Sharing to Instagram Stories is even simpler. We’ll use a UIPasteboard which is a simple object for sharing data to another app.

func shareToInstagramStories(image: UIImage) {
    // NOTE: you need a different custom URL scheme for Stories, instagram-stories, add it to your Info.plist!
    guard let instagramUrl = URL(string: "instagram-stories://share") else {
        return
    }

    if UIApplication.shared.canOpenURL(instagramUrl) {
        let pasterboardItems = [["com.instagram.sharedSticker.backgroundImage": image as Any]]
        UIPasteboard.general.setItems(pasterboardItems)
        UIApplication.shared.open(instagramUrl)
    } else {
        // Instagram app is not installed or can't be opened, pop up an alert
    }
}

And… that’s it! This opens the customisation screen for Instagram Stories with your image passed as parameter! The user can add more stickers, text, animations, etc. on top of your background image.

I hope this post was helpful. :)

References

tweet Share