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>