Recently in one of our Unity projects, we wanted to allow the user to share an image on Instagram. This sounds like a fairly straightforward process, and it should be, given we’re talking about one of the largest social networks.

Unfortunately, the information for this process is scarce and far from consistent.

Since the release of our project, some Unity plugins appeared on the Asset Store that supposedly help you do this. However, given our hacker nature we feel a lot more comfortable when we know exactly what’s going on inside our code, right?

That’s why today I bring you a brief explanation on how to accomplish this on iOS.

Step 1 – Create the native code

The header file (InstagramShare.h):

The implementation file (InstagramShare.m):

The really important part to retain here is this:

We start by asking the OS if it can open an Instagram file by using the “canOpenURL” method of the UIApplication instance. If so, we grab the image path sent by Unity, create a UIImage from it and pass it to the UIDocumentInteractionController.

The UIDocumentInteractionController is the king here and what it does is provides in-app support for managing user interactions with files in the local system – i.e. you can use it to open any kind of file or image with an appropriate application.

Notice you’ll have to save the header and the implementation files on your Assets folder under “Assets/Plugins/iOS”.

Step 2 –  Create the bridge:

This file is where the magic happens by making the bridge between Unity and the native code in Objective-C. Since the methods are static you can call them from anywhere on your code – really handy!

Step 3 – Wrap it up

Although using the files we just created we can share any image (converted to a byte array), here we’ll show you how to grab a shot from any in-game camera – we’ll use the main one for demonstration purposes.

You’ll notice the “PostToInstagram” method is a co-routine, and that’s because we need to wait until the end of the current frame to capture a render texture.

Unity Instagram Share

Unity Instagram Share

And here’s our glorious app! On the left, the Unity app with the share button. On the middle, the UIDocumentInteractionController asking us what to do with the file. And on the right, our beautiful image inside Instagram with a hipster filter to make it look even cooler!

That’s it. You can now share your images on Instagram from your Unity projects! Hope this is handy for you and let us know if you have any questions or suggestions for upcoming posts!