How to share an image on Instagram in iOS?

Hope this answer will resolve your query. This will directly opens library folder in Instagram instead of Camera.

NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
    NSURL *videoFilePath = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[request downloadDestinationPath]]]; // Your local path to the video
    NSString *caption = @"Some Preloaded Caption";
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeVideoAtPathToSavedPhotosAlbum:videoFilePath completionBlock:^(NSURL *assetURL, NSError *error) {
        NSString *escapedString   = [self urlencodedString:videoFilePath.absoluteString];
        NSString *escapedCaption  = [self urlencodedString:caption];
        NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@",escapedString,escapedCaption]];
        if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
            [[UIApplication sharedApplication] openURL:instagramURL];
        }
    }];

Finally I got the answer. you can not directly post an image on instagram. You have to rediredt your image with UIDocumentInteractionController.

@property (nonatomic, retain) UIDocumentInteractionController *dic;    

CGRect rect = CGRectMake(0 ,0 , 0, 0);
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndImageContext();
NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.igo"];

NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"file://%@", jpgPath]];
self.dic.UTI = @"com.instagram.photo";
self.dic = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
self.dic=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.dic presentOpenInMenuFromRect: rect    inView: self.view animated: YES ];


- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
     UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
     interactionController.delegate = interactionDelegate;
     return interactionController;
}

NOTE : once you redirect to instagram app you can not back to your app. you have to open your app again

Download source from here


You can use one of the provided by Instagram url scheme

enter image description here

  1. Instagram oficial doc here

  2. Share with UIDocumentInteractionController

     final class InstagramPublisher : NSObject {
    
     private var documentsController:UIDocumentInteractionController = UIDocumentInteractionController()
    
     func postImage(image: UIImage, view: UIView, result:((Bool)->Void)? = nil) {
         guard let instagramURL = NSURL(string: "instagram://app") else {
             if let result = result {
                 result(false)
             }
         return
     }
         if UIApplication.sharedApplication().canOpenURL(instagramURL) {
             let jpgPath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagrammFotoToShareName.igo")
             if let image = UIImageJPEGRepresentation(image, 1.0) {
                 image.writeToFile(jpgPath, atomically: true)
                 let fileURL = NSURL.fileURLWithPath(jpgPath)
                 documentsController.URL = fileURL
                 documentsController.UTI = "com.instagram.exclusivegram"
                 documentsController.presentOpenInMenuFromRect(view.bounds, inView: view, animated: true)
                 if let result = result {
                     result(true)
                 }
             } else if let result = result {
                 result(false)
             }
         } else {
             if let result = result {
                 result(false)
             }
         }
         }
     }
    
  3. Share with direct redirect

     import Photos
    
     final class InstagramPublisher : NSObject {
    
     func postImage(image: UIImage, result:((Bool)->Void)? = nil) {
     guard let instagramURL = NSURL(string: "instagram://app") else {
         if let result = result {
             result(false)
         }
         return
     }
    
     let image = image.scaleImageWithAspectToWidth(640)
    
     do {
         try PHPhotoLibrary.sharedPhotoLibrary().performChangesAndWait {
             let request = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
    
             let assetID = request.placeholderForCreatedAsset?.localIdentifier ?? ""
             let shareURL = "instagram://library?LocalIdentifier=" + assetID
    
             if UIApplication.sharedApplication().canOpenURL(instagramURL) {
                 if let urlForRedirect = NSURL(string: shareURL) {
                     UIApplication.sharedApplication().openURL(urlForRedirect)
                 }
             }
         }
     } catch {
         if let result = result {
             result(false)
         }
     }
     }
     }
    
  4. extension for resize photo to recommended size

     import UIKit
    
     extension UIImage {
         // MARK: - UIImage+Resize
    
         func scaleImageWithAspectToWidth(toWidth:CGFloat) -> UIImage {
             let oldWidth:CGFloat = size.width
             let scaleFactor:CGFloat = toWidth / oldWidth
    
             let newHeight = self.size.height * scaleFactor
             let newWidth = oldWidth * scaleFactor;
    
             UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
             drawInRect(CGRectMake(0, 0, newWidth, newHeight))
             let newImage = UIGraphicsGetImageFromCurrentImageContext()
             UIGraphicsEndImageContext()
             return newImage
         }
     }
    
  5. Don't forget to add required scheme in plist

  <key>LSApplicationQueriesSchemes</key>
  <array>
       <string>instagram</string> 
  </array>

Here is a full tested code to Upload image + caption text to Instagram..

in.h file

//Instagram
@property (nonatomic, retain) UIDocumentInteractionController *documentController;

-(void)instaGramWallPost
{
            NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
            if([[UIApplication sharedApplication] canOpenURL:instagramURL]) //check for App is install or not
            {
                NSData *imageData = UIImagePNGRepresentation(imge); //convert image into .png format.
                NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
                NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
                NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"insta.igo"]]; //add our image to the path
                [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
                NSLog(@"image saved");

                CGRect rect = CGRectMake(0 ,0 , 0, 0);
                UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
                [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
                UIGraphicsEndImageContext();
                NSString *fileNameToSave = [NSString stringWithFormat:@"Documents/insta.igo"];
                NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:fileNameToSave];
                NSLog(@"jpg path %@",jpgPath);
                NSString *newJpgPath = [NSString stringWithFormat:@"file://%@",jpgPath];
                NSLog(@"with File path %@",newJpgPath);
                NSURL *igImageHookFile = [[NSURL alloc]initFileURLWithPath:newJpgPath];
                NSLog(@"url Path %@",igImageHookFile);

                self.documentController.UTI = @"com.instagram.exclusivegram";
                self.documentController = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
                self.documentController=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
                NSString *caption = @"#Your Text"; //settext as Default Caption
                self.documentController.annotation=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@",caption],@"InstagramCaption", nil];
                [self.documentController presentOpenInMenuFromRect:rect inView: self.view animated:YES];
            }
            else
            {
                 NSLog (@"Instagram not found");
            }
}

- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
    NSLog(@"file url %@",fileURL);
    UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
    interactionController.delegate = interactionDelegate;

    return interactionController;
}

OR

-(void)instaGramWallPost
{
    NSURL *myURL = [NSURL URLWithString:@"Your image url"];
    NSData * imageData = [[NSData alloc] initWithContentsOfURL:myURL];
    UIImage *imgShare = [[UIImage alloc] initWithData:imageData];

    NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];

    if([[UIApplication sharedApplication] canOpenURL:instagramURL]) //check for App is install or not
    {
        UIImage *imageToUse = imgShare;
        NSString *documentDirectory=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString *saveImagePath=[documentDirectory stringByAppendingPathComponent:@"Image.igo"];
        NSData *imageData=UIImagePNGRepresentation(imageToUse);
        [imageData writeToFile:saveImagePath atomically:YES];
        NSURL *imageURL=[NSURL fileURLWithPath:saveImagePath];
        self.documentController=[[UIDocumentInteractionController alloc]init];
        self.documentController = [UIDocumentInteractionController interactionControllerWithURL:imageURL];
        self.documentController.delegate = self;
        self.documentController.annotation = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Testing"], @"InstagramCaption", nil];
        self.documentController.UTI = @"com.instagram.exclusivegram";
        UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
        [self.documentController presentOpenInMenuFromRect:CGRectMake(1, 1, 1, 1) inView:vc.view animated:YES];
    }
    else {
        DisplayAlertWithTitle(@"Instagram not found", @"")
    }
}

and Write this to .plist

<key>LSApplicationQueriesSchemes</key>
    <array>
        <string>instagram</string>
    </array>