89

My client wants to share an image on Instagram, Twitter, Facebook.

I have done Twitter and Facebook but did not find any API or any thing on internet to share image on Instagram. Is it possible to share image on Instagram? if yes then how?

When I check the developer site of Instagram I have found the Libraries of Ruby on Rails and Python. But there are no documentation of iOS Sdk

I have get token from instagram as per instagram.com/developer but now don't know what to do next step for sharing with instagram image.

Braiam
  • 1
  • 11
  • 47
  • 78
Hiren
  • 12,720
  • 7
  • 52
  • 72
  • Any idea on http://stackoverflow.com/questions/28858512/instagram-ios-hooks-getting-the-posted-media-id-back?rq=1 ? – Ashok Jan 28 '16 at 09:10

18 Answers18

70

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

Hiren
  • 12,720
  • 7
  • 52
  • 72
  • where is the function setupControllerWithURL or it do ? – khaled Aug 08 '12 at 14:42
  • hey i have used your code.. it opens a actionsheet with "instagram" option but when i click on that nothing happens..can you please help me – Surender Rathore Aug 16 '12 at 14:21
  • 3
    @SurenderRathore you have to scale your image into into 612*612 and save into .ig format .ig shows that you want to open your image into instagram and you have to test in your iPhone or iPod upto version 4.3 . iPad is not supported – Hiren Aug 17 '12 at 04:42
  • How can I get followers list from Instagram? – Dee Sep 26 '12 at 09:15
  • @HiRen: Thanks, it is working well. Now I want to share some text also with image like we do in facebook and twitter. How can I do this for instagram? – Manthan Apr 02 '13 at 05:59
  • @user2135853 If you are using this code then you are already moved to native instagram app. So you can use all the functionality of app – Hiren Apr 02 '13 at 06:09
  • 1
    @HiRen: Yes, you are right but in my app I am taking screenshot of a view and and then sharing that screenshot via instagram app and its perfectly working well. But I also want to pass some static text with that screenshot. If you have any idea please help me. There is a demo code on github for DMACtivityInstagram and you can see from there what I m trying to say. Thanks in advance. – Manthan Apr 02 '13 at 06:17
  • @HiRen:Did u find anything on how to share text with image on instagram with this code? Thanks... – Manthan Apr 02 '13 at 09:59
  • @HiRen: I got my answer. Added the line below and it worked for me. self.dic.annotation = [NSDictionary dictionaryWithObject:@"Here write what you want to share" forKey:@"InstagramCaption"]; – Manthan Apr 02 '13 at 10:59
  • @HiRen: I am opening Instagram from my app for sharing and it works fine. But Is it possible that Can I check Whether the user has shared it successfully or not? Means I want to perform some action in my DB when user successfully shares an image. How can i do this? – Manthan Apr 25 '13 at 09:27
  • @ManthanPatel this is not possible because once you redirect to Instagram you can not come back to your app. If you want this then you can get images from Instagram and check if image is in the list then change the status in DB – Hiren Apr 25 '13 at 11:37
  • @NSNull: Is it possible that if we click on a button and it directly navigates me to the native instagram app? You can see what I want from the link [http://stackoverflow.com/questions/16954810/remove-activityviewcontroller-when-sharing-in-ios6/16955128?noredirect=1#16955128] – Manthan Jun 07 '13 at 07:05
  • once i redirect to instagram app i can not back my app is right ? or possible to back my app Please reply me – kirti Chavda Aug 08 '13 at 14:18
  • Yes once you redirect to instagram you can not back to your app. – Hiren Aug 09 '13 at 06:09
  • Is there a way to get Instagram's post_id of what the user just shared? – anthoprotic Jan 20 '14 at 20:00
  • @sabir post new question in SO. Please check this http://stackoverflow.com/questions/11559518/fetching-user-profile-data-from-linkedin-in-iphone-sdk. I have never worked on LinkedIn API. – Hiren Mar 06 '14 at 07:34
  • hi @Hiren i have done the linked in can you please share me how can i get complete profile information from instragram.. – sabir Mar 06 '14 at 07:38
  • @sabir please read the docs of instagram. It will help to you a lot. http://instagram.com/developer/endpoints/users/ – Hiren Mar 06 '14 at 09:26
  • 2
    Using this line gave me a crash in iOS 6: NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"file://%@", jpgPath]]; Using this works in both: NSURL *igImageHookFile = [NSURL fileURLWithPath:jpgPath]; Might be worth editing the answer accordingly, unless I'm missing something? – weienw Mar 28 '14 at 18:27
  • @weienw, While I came to comment, you have already mentioned it. – arunit21 Sep 11 '14 at 10:31
  • 1
    is this jus me, or does anyone else wants to say "hey Instagram, you were developer once, why are you making our life this hard?" – Chris Chen Aug 17 '16 at 05:43
27

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>
Hardik Thakkar
  • 15,269
  • 2
  • 94
  • 81
24

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>
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
hbk
  • 10,908
  • 11
  • 91
  • 124
  • 1
    Tried a bunch of other stuff from other answers and only this worked (at least for videos. The "instagram://library?LocalIdentifier=" was what did it. Many thanks! – Bjorn Roche Jan 19 '17 at 16:54
  • The share with direct redirect (which is by far the best solution IMO) no longer works for me - Instagram opens at the library page but doesn't pre-select an image. Does you have any idea what might have changed with this URL scheme? Are you experiencing similar failures with the latest version of Instagram on iOS? – urchino Jun 13 '17 at 08:51
  • @gbk This code works for me. But I have new requirement sahre multiple photos in Instagram. Like Instagram have new option multiple upload and display like slide view. Do you how to do this? Please help me. – Ekta Padaliya Oct 12 '17 at 11:40
  • Holy sh*t. Thank you for this. I've been banging my head against a wall for the past day trying to get sharing to instagram from my app to work nicely. – Jesse S. Sep 07 '18 at 16:55
  • @gbk, I did. :) – Jesse S. Jan 04 '19 at 22:05
  • 3
    only 3'd variant is working for me for ios 13, btw dont forget to add NSPhotoLibraryUsageDescription App needs your nude photos. – serg_zhd Oct 02 '19 at 16:33
14

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];
        }
    }];
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Pratik Patel
  • 1,393
  • 12
  • 18
10

if you don't want to use UIDocumentInteractionController

import Photos

...

func postImageToInstagram(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(SocialShare.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
        if error != nil {
            print(error)
        }

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        let fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
        if let lastAsset = fetchResult.firstObject as? PHAsset {
            let localIdentifier = lastAsset.localIdentifier
            let u = "instagram://library?LocalIdentifier=" + localIdentifier
            let url = NSURL(string: u)!
            if UIApplication.sharedApplication().canOpenURL(url) {
                UIApplication.sharedApplication().openURL(NSURL(string: u)!)
            } else {
                let alertController = UIAlertController(title: "Error", message: "Instagram is not installed", preferredStyle: .Alert)
                alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
                self.presentViewController(alertController, animated: true, completion: nil)
            }

        }
    }
Zuhair Hussain
  • 823
  • 9
  • 19
9

For iOS 6 and above, you can use this UIActivity to upload images to Instagram which has the same workflow using iOS hooks but simplifies development:

https://github.com/coryalder/DMActivityInstagram

Chintan Patel
  • 3,175
  • 3
  • 30
  • 36
  • hi @Chintan Patel how can i get user profile information in if you have any sample source please share with us – sabir Mar 06 '14 at 07:04
6

this is correct answer which i implement with detail. In .h file

 UIImageView *imageMain;
 @property (nonatomic, strong) UIDocumentInteractionController *documentController;

in.m file only write

 NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
 if([[UIApplication sharedApplication] canOpenURL:instagramURL])
 {
      CGFloat cropVal = (imageMain.image.size.height > imageMain.image.size.width ? imageMain.image.size.width : imageMain.image.size.height);

      cropVal *= [imageMain.image scale];

      CGRect cropRect = (CGRect){.size.height = cropVal, .size.width = cropVal};
      CGImageRef imageRef = CGImageCreateWithImageInRect([imageMain.image CGImage], cropRect);

      NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 1.0);
      CGImageRelease(imageRef);

      NSString *writePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"instagram.igo"];
      if (![imageData writeToFile:writePath atomically:YES]) {
      // failure
           NSLog(@"image save failed to path %@", writePath);
           return;
      } else {
      // success.
      }

      // send it to instagram.
      NSURL *fileURL = [NSURL fileURLWithPath:writePath];
      self.documentController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
      self.documentController.delegate = self;
      [self.documentController setUTI:@"com.instagram.exclusivegram"];
      [self.documentController setAnnotation:@{@"InstagramCaption" : @"We are making fun"}];
      [self.documentController presentOpenInMenuFromRect:CGRectMake(0, 0, 320, 480) inView:self.view animated:YES];
 }
 else
 {
      NSLog (@"Instagram not found");

 }

For sure you will get result. E.g you will see popover from bottom with instagram image.Click on it and have fun.

Paulo Miguel Almeida
  • 2,114
  • 31
  • 36
Lalit
  • 264
  • 3
  • 10
5

I tried this in my application and it is working perfectly (Swift)

import Foundation

import UIKit

class InstagramManager: NSObject, UIDocumentInteractionControllerDelegate {

    private let kInstagramURL = "instagram://"
    private let kUTI = "com.instagram.exclusivegram"
    private let kfileNameExtension = "instagram.igo"
    private let kAlertViewTitle = "Error"
    private let kAlertViewMessage = "Please install the Instagram application"

    var documentInteractionController = UIDocumentInteractionController()

    // singleton manager
    class var sharedManager: InstagramManager {
        struct Singleton {
            static let instance = InstagramManager()
        }
        return Singleton.instance
    }

    func postImageToInstagramWithCaption(imageInstagram: UIImage, instagramCaption: String, view: UIView) {
        // called to post image with caption to the instagram application

        let instagramURL = NSURL(string: kInstagramURL)
        if UIApplication.sharedApplication().canOpenURL(instagramURL!) {
            let jpgPath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(kfileNameExtension)
            UIImageJPEGRepresentation(imageInstagram, 1.0)!.writeToFile(jpgPath, atomically: true)
            let rect = CGRectMake(0,0,612,612)
            let fileURL = NSURL.fileURLWithPath(jpgPath)
            documentInteractionController.URL = fileURL
            documentInteractionController.delegate = self
            documentInteractionController.UTI = kUTI

            // adding caption for the image
            documentInteractionController.annotation = ["InstagramCaption": instagramCaption]
            documentInteractionController.presentOpenInMenuFromRect(rect, inView: view, animated: true)
        }
        else {

            // alert displayed when the instagram application is not available in the device
            UIAlertView(title: kAlertViewTitle, message: kAlertViewMessage, delegate:nil, cancelButtonTitle:"Ok").show()
        }
    }
}


 func sendToInstagram(){

     let image = postImage

             InstagramManager.sharedManager.postImageToInstagramWithCaption(image!, instagramCaption: "\(description)", view: self.view)

 }
2

Here is the correct answer. you cannot directly post an image on Instagram. You need to redirect to Instagram using UIDocumentInteractionController...

NSString* imagePath = [NSString stringWithFormat:@"%@/instagramShare.igo", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
    
UIImage *instagramImage = [UIImage imageNamed:@"imagename you want to share"];
[UIImagePNGRepresentation(instagramImage) writeToFile:imagePath atomically:YES];
NSLog(@"Image Size >>> %@", NSStringFromCGSize(instagramImage.size));
    
self.dic=[UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:imagePath]];
self.dic.delegate = self;
self.dic.UTI = @"com.instagram.exclusivegram";
[self.dic presentOpenInMenuFromRect: self.view.frame inView:self.view animated:YES ];

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

aturan23
  • 4,798
  • 4
  • 28
  • 52
Anooj VM
  • 2,593
  • 22
  • 19
2

You can do that without using the UIDocumentInteractionController and go straight to Instagram with these 3 methods:

It works just like all the other famous app does. The code is written in Objective c, so you can translate it to swift if you want. What you need to do is saving your image to the device and use a URLScheme

add this inside your .m file

#import <Photos/Photos.h>

First you need to save your UIImage to the device with this method:

-(void)savePostsPhotoBeforeSharing
{
    UIImageWriteToSavedPhotosAlbum([UIImage imageNamed:@"image_file_name.jpg"], self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

This method is the callback for saving the image to your device:

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo;
{
    [self sharePostOnInstagram];

}

After the image is saved to the device, you need to query the image you just saved and get it as a PHAsset

-(void)sharePostOnInstagram
{
    PHFetchOptions *fetchOptions = [PHFetchOptions new];
    fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO],];
    __block PHAsset *assetToShare;
    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
    [result enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
        assetToShare = asset;


    }];


    if([assetToShare isKindOfClass:[PHAsset class]])
    {
        NSString *localIdentifier = assetToShare.localIdentifier;
        NSString *urlString = [NSString stringWithFormat:@"instagram://library?LocalIdentifier=%@",localIdentifier];
        NSURL *instagramURL = [NSURL URLWithString:urlString];
        if ([[UIApplication sharedApplication] canOpenURL: instagramURL])
        {
            [[UIApplication sharedApplication] openURL: instagramURL];
        } else
        {
            // can not share with whats app
            NSLog(@"No instagram installed");
        }

    }
}

And dont forget to put this in your info.plist under LSApplicationQueriesSchemes

<string>instagram</string>

aviv_elk
  • 416
  • 1
  • 9
  • 21
2
    @import Photos;

    -(void)shareOnInstagram:(UIImage*)imageInstagram {

        [self authorizePHAssest:imageInstagram];
    }

    -(void)authorizePHAssest:(UIImage *)aImage{

        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];

        if (status == PHAuthorizationStatusAuthorized) {
            // Access has been granted.
            [self savePostsPhotoBeforeSharing:aImage];
        }

        else if (status == PHAuthorizationStatusDenied) {
            // Access has been denied.
        }

        else if (status == PHAuthorizationStatusNotDetermined) {

            // Access has not been determined.
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

                if (status == PHAuthorizationStatusAuthorized) {
                    // Access has been granted.
                    [self savePostsPhotoBeforeSharing:aImage];
                }
            }];
        }

        else if (status == PHAuthorizationStatusRestricted) {
            // Restricted access - normally won't happen.
        }
    }
    -(void)saveImageInDeviceBeforeSharing:(UIImage *)aImage
    {
        UIImageWriteToSavedPhotosAlbum(aImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }

    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo;
    {
        if (error == nil){
            [self sharePostOnInstagram];
        }
    }

    -(void)shareImageOnInstagram
    {
        PHFetchOptions *fetchOptions = [PHFetchOptions new];
        fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:false]];
        PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];

        __block PHAsset *assetToShare = [result firstObject];

        if([assetToShare isKindOfClass:[PHAsset class]])
        {
            NSString *localIdentifier = assetToShare.localIdentifier;
            NSString *urlString = [NSString stringWithFormat:@"instagram://library?LocalIdentifier=%@",localIdentifier];
            NSURL *instagramURL = [NSURL URLWithString:urlString];
            if ([[UIApplication sharedApplication] canOpenURL: instagramURL])
            {
                [[UIApplication sharedApplication] openURL:instagramURL options:@{} completionHandler:nil];
            } else
            {
                NSLog(@"No instagram installed");
            }
        }
    }

NOTE:- IMP TODO:- Add below key in Info.plist

<key>LSApplicationQueriesSchemes</key>
<array>
<string>instagram</string>
</array>
Hardik Thakkar
  • 15,269
  • 2
  • 94
  • 81
CrazyPro007
  • 1,006
  • 9
  • 15
  • The only problem with this is, that if the user has set ```limited``` photo library access, it won't show the latest image, instead the Instagram will show the latest image out of all the images that the user has selected or allowed before via the photo library view controller thing. – Supertecnoboff Feb 01 '23 at 20:15
1
- (void) shareImageWithInstagram
{
    NSURL *instagramURL = [NSURL URLWithString:@"instagram://"];
    if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
    {
        UICachedFileMgr* mgr = _gCachedManger;
        UIImage* photoImage = [mgr imageWithUrl:_imageView.image];
        NSData* imageData = UIImagePNGRepresentation(photoImage);
        NSString* captionString = [NSString  stringWithFormat:@"ANY_TAG",];
        NSString* imagePath = [UIUtils documentDirectoryWithSubpath:@"image.igo"];
        [imageData writeToFile:imagePath atomically:NO];
        NSURL* fileURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"file://%@",imagePath]];

        self.docFile = [[self setupControllerWithURL:fileURL usingDelegate:self]retain];
        self.docFile.annotation = [NSDictionary dictionaryWithObject: captionString
                                                     forKey:@"InstagramCaption"];
        self.docFile.UTI = @"com.instagram.photo";

        // OPEN THE HOOK
        [self.docFile presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
    }
    else
    {
        [UIUtils messageAlert:@"Instagram not installed in this device!\nTo share image please install instagram." title:nil delegate:nil];
    }
}

I tried this in my application and it will definitely work

neha_sinha19
  • 514
  • 4
  • 9
  • Maybe you should explain `UIUtils` & `UICachedFileMgr`? – Raptor Jul 17 '14 at 08:00
  • Understand. Suggest to edit your answer to provide more details – Raptor Nov 13 '14 at 02:13
  • @Raptor: Please download the sample app from the following: [link](https://github.com/sinha-neha/iOSHUB/tree/PostToIGSample) – neha_sinha19 Nov 13 '14 at 10:16
  • UIUtils is a class that I have created in order to manage utility methods.It is derived from NSObject. I have added the messageAlert method to show the alert view. In the sample app whose link I have provided above, you can find UIUtils class. Hopefully, you will understand. – neha_sinha19 Nov 13 '14 at 10:22
1

As for me, the best and the easiest way described here Share photo to Instagram from my iOS App

You need to save image on device using .igo format, then use "UIDocumentInteractionController" to send local path Instagram app. Don't forget to set "UIDocumentInteractionControllerDelegate"

My advice is to add something like:

NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) 
{
 <your code>
}
Community
  • 1
  • 1
Dmitry Soloviov
  • 491
  • 1
  • 5
  • 8
1
NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];

if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{

    NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/Insta_Images/%@",@"shareImage.png"]];


    NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"file://%@", jpgPath]];


    docController.UTI = @"com.instagram.photo";

    docController = [self setupControllerWithURL:igImageHookFile usingDelegate:self];

    docController =[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];

    docController.delegate=self;

    [docController presentOpenInMenuFromRect:CGRectMake(0 ,0 , 612, 612) inView:self.view animated:YES];
benka
  • 4,732
  • 35
  • 47
  • 58
fkb
  • 11
  • 1
1

I noticed if you put URL pointing to image to activityItems instead of UIImage, Copy to Instagram activity item appears itself, and you don't have to do anything else. Please note that String objects inside activityItems would be discarded and there is no way to prefill caption in Instagram. If you still want to hint user to post particular caption, you'd need to create custom activity where you copy that text to clipboard and let user know about it, like in this gist.

Almas Sapargali
  • 451
  • 4
  • 9
0

I Used this code:

    NSString* filePathStr = [[NSBundle mainBundle] pathForResource:@"UMS_social_demo" ofType:@"png"];
NSURL* fileUrl = [NSURL fileURLWithPath:filePathStr];

NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.igo"];
[[NSData dataWithContentsOfURL:fileUrl] writeToFile:jpgPath atomically:YES];

NSURL* documentURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@", jpgPath]];

UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: documentURL];
self.interactionController = interactionController;
interactionController.delegate = self;
interactionController.UTI = @"com.instagram.photo";
CGRect rect = CGRectMake(0 ,0 , 0, 0);
[interactionController presentOpenInMenuFromRect:rect inView:self.view animated:YES];
dhar
  • 31
  • 2
0
-(void)shareOnInstagram {

    CGRect rect = CGRectMake(self.view.frame.size.width*0.375 ,self.view.frame.size.height/2 , 0, 0);



    NSString * saveImagePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/ShareInstragramImage.igo"];

    [UIImagePNGRepresentation(_image) writeToFile:saveImagePath atomically:YES];

    NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"file://%@", saveImagePath]];

    self.documentController=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];

    self.documentController.UTI = @"com.instagram.exclusivegram";
    self.documentController = [self setupControllerWithURL:igImageHookFile usingDelegate:self];

    [self.documentController 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;
}
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – thewaywewere Jun 19 '17 at 05:23
0
NSURL *myURL = [NSURL URLWithString:sampleImageURL];
NSData * imageData = [[NSData alloc] initWithContentsOfURL:myURL];
UIImage *imageToUse = [[UIImage alloc] initWithData:imageData];
NSString *documentDirectory=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *saveImagePath=[documentDirectory stringByAppendingPathComponent:@"Image.ig"];
[imageData writeToFile:saveImagePath atomically:YES];
NSURL *imageURL=[NSURL fileURLWithPath:saveImagePath];
self.documentController = [UIDocumentInteractionController interactionControllerWithURL:imageURL];
self.documentController.delegate = self;
self.documentController.annotation = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@""], @"", nil];
self.documentController.UTI = @"com.instagram.exclusivegram";
[self.documentController presentOpenInMenuFromRect:CGRectMake(1, 1, 1, 1) inView:self.view animated:YES];
aturan23
  • 4,798
  • 4
  • 28
  • 52