Instagram post with Swift

Instagram-SwiftIt’s simple but hard to find the Swift version. Here it is…








import Foundation
import UIKit

class InstagramDemo: UIViewController, UIDocumentInteractionControllerDelegate
    private var YourImage:UIImage! //Replace with your image
    private var documentController:UIDocumentInteractionController!
    override func viewDidLoad() {
    func postToInstagram(){
        let instagramUrl = NSURL(string: "instagram://app")
            //Instagram App avaible
            let imageData = UIImageJPEGRepresentation(YourImage, 100)
            let captionString = "Your Caption"
            let writePath = NSTemporaryDirectory().stringByAppendingPathComponent("instagram.igo")
            if(!imageData.writeToFile(writePath, atomically: true)){
                //Fail to write. Don't post it
            } else{
                //Safe to post
                let fileURL = NSURL(fileURLWithPath: writePath)
                self.documentController = UIDocumentInteractionController(URL: fileURL!)
                self.documentController.delegate = self
                self.documentController.UTI = "com.instagram.exclusivegram"
                self.documentController.annotation =  NSDictionary(object: captionString, forKey: "InstagramCaption")
                self.documentController.presentOpenInMenuFromRect(self.view.frame, inView: self.view, animated: true)
        } else {
            //Instagram App NOT avaible...

Selim Anaç

Selim Anaç

More than 20 years of working experience at digital products as games/advergames, mobile & desktop apps and online software production. Multi-discipline software developer, team leader. A video game addict.

  • Burhan Aksendir

    Çok teşekkür ederim. Gerçekten arıyordum bunu.

  • oraneedwards

    whoever you are, Thank You! <3. tweet me if you wanna build a game together @oraneESCENTRICK

  • Alex Marshall

    Hmm it doesn’t seem to like this line:

    let writePath = NSTemporaryDirectory().stringByAppendingPathComponent(“instagram.igo”)

    it complains: stringByAppendingPathComponent is unavailable. UseURLByAppendingPathComponent on NSURL instead. Perhaps this is for an older version of swift?

  • Dev Elope

    What do I need to change if I want it to go direct to Instagram and not give me options like Facebook, Twitter, etc.? Thanks!

    • It wasn’t possible when i developed this app because of there wasn’t any instagram sdk available for ios. Also instagram doesn’t allow us to post media with it’s api.
      This is why i use this method. Looks like still this is the only way to do this