How to share Image in Instagram from one application

4.2k views Asked by At

I am trying to share an image on the Instagram application through my application.

Please check my code below and please let me know where I have gone wrong.

_instagramURL = [NSURL URLWithString:[NSString stringWithFormat: @"instagram://media?id=%@",[SingletoneClass sharedSingleTone].imageId]];

if ([[UIApplication sharedApplication] canOpenURL:_instagramURL]) {
    self.dic = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[SingletoneClass sharedSingleTone].imagePath]];
    self.dic.delegate = self;
    self.dic.UTI = @"com.instagram.exclusivegram";
    self.dic.annotation = [NSDictionary dictionaryWithObject:[SingletoneClass sharedSingleTone].captionStr forKey:@"InstagramCaption"];
    [self.dic presentOpenInMenuFromRect: CGRectZero inView:self.view animated:YES ];
}
else {
    UIAlertController *alert = [[SingletoneClass sharedSingleTone] setAlertControllerWithTitle:@"" message:@"Instagram is not present in your device" andCallback:^(id actionResponse) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];
    [self presentViewController:alert animated:YES completion:nil];
}

If above code is correct, then please let me know, from where I can find the imageId?

2

There are 2 answers

0
Tajinder singh On

Check Below code for share image on Instagram , its working fine

import

-(void)shareImageOnInstagram:(UIImage *)image { if(![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"instagram://"]]) { //Your device doesn't have Instagram app. return; }

    //__weak typeof(self) weakSelf = self;
    __block PHFetchResult *photosAsset;
    __block PHObjectPlaceholder *placeholder;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest* createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        placeholder = [createAssetRequest placeholderForCreatedAsset];
        photosAsset = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[placeholder.localIdentifier] options:nil];

    } completionHandler:^(BOOL success, NSError *error) {
        if (success) {
            PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
            requestOptions.synchronous = YES;
            PHFetchOptions *allPhotosOptions = [PHFetchOptions new];
            allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

            NSString *identifier = placeholder.localIdentifier;
            dispatch_async(dispatch_get_main_queue(), ^{

            NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?LocalIdentifier=%@",identifier]];

            if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
                [[UIApplication sharedApplication] openURL:instagramURL options:@{} completionHandler:^(BOOL success) {
                }];
            }
            });
        }
    }];

}

1
Sambit Prakash On

Finally, I got the solution. We need to save the image in Document directory. Instagram app can retrieve the image from Document directory.

NSData *imagedata = UIImageJPEGRepresentation(image, 0.5);
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)

Then by using UIDocumentInteractionController, we can share the image in Instagram app. Before sharing the image, you need to be sure that Instagram app is present in the device.

- (void) shareImageToInstagram {
    _instagramURL = [NSURL URLWithString:[NSString stringWithFormat: @"instagram://app"]];

    if ([[UIApplication sharedApplication] canOpenURL:_instagramURL])   
    {
        self.dic = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[SingletoneClass sharedSingleTone].imagePath]];
        self.dic.delegate = self;
        self.dic.UTI = @"com.instagram.photo";
        self.dic.annotation = [NSDictionary dictionaryWithObjectsAndKeys:[SingletoneClass sharedSingleTone].captionStr,@"InstagramCaption", nil];
        [self.dic presentOpenInMenuFromRect: CGRectZero inView:self.view animated:YES ];
    }
    else 
    {
        UIAlertController *alert = [[SingletoneClass sharedSingleTone] setAlertControllerWithTitle:@"" message:@"Instagram is not present in your device" andCallback:^(id actionResponse) {
            [alert dismissViewControllerAnimated:YES completion:nil];
        }];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

You can refer the following links for more information. https://www.instagram.com/developer/mobile-sharing/iphone-hooks/ and Share photo to Instagram from my iOS App