Instagram hooks pre-select media issue

﹥>﹥吖頭↗ 提交于 2019-11-27 12:54:29

instagram://library?AssetPath=\(assetsLibraryUrl) stopped working a while ago. Instagram developers probably moved to Photos framework and no longer use the AssetsLibrary.

Having this assumption I tried several other parameter names and found that instagram://library?LocalIdentifier=\(localID) where localId is the localIdentifier of your PHAsset works for now.

This is still as undocumented as it was so it can break in any future version of the Instagram.

Resuming this task after a long time and considering the borisgolovnev's answer and ALAssetsLibrary is deprecated, the final solution is:

- (void)saveToCameraRollOpt2:(NSURL *)srcURL
{
    __block PHAssetChangeRequest *_mChangeRequest = nil;
    __block PHObjectPlaceholder *placeholder;

    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

        NSData *pngData = [NSData dataWithContentsOfURL:srcURL];
        UIImage *image = [UIImage imageWithData:pngData];

        _mChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

        placeholder = _mChangeRequest.placeholderForCreatedAsset;

    } completionHandler:^(BOOL success, NSError *error) {

        if (success) {
            [self loadCameraRollAssetToInstagram:[placeholder localIdentifier]];
        }
        else {
            NSLog(@"write error : %@",error);
            [self showAlert:@"Error" msg:@"Error saving in camera roll" action:nil];
        }
    }];
}

- (void)loadCameraRollAssetToInstagram:(NSString *)localId
{
    NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?LocalIdentifier=\%@", localId]];

    if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
        [[UIApplication sharedApplication] openURL:instagramURL options:@{} completionHandler:nil];
    } else {
        [self showAlert:@"Error" msg:@"Instagram app is not installed" action:nil];
    }
}

- (NSString*)urlencodedString:(NSString *)message
{
    return [message stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
}

Don't forget

#import <Photos/Photos.h>

Add `NSPhotoLibraryUsageDescription` and `QueriesSchemes` inside .plist file

<key>NSPhotoLibraryUsageDescription</key>
<string>Need permission to access to manage your photos library</string>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>instagram</string>
</array>

@borisgolovnev's solution actually works. You can get the localIdentifier of your last saved video using the code below. Passing it with instagram://library?LocalIdentifier=(localID) opens Instagram with your video selected.

let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending:false)]
let fetchResult = PHAsset.fetchAssetsWithMediaType(.Video, options: fetchOptions)
if let lastAsset = fetchResult.firstObject as? PHAsset {
    self.localIdentifier = lastAsset.localIdentifier
}
Pratik Patel

use this code

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];
        }
    }];
}

Instagram will only shows those iamges/videos which are saved at path which you set in instagramURL. That path should be absolute.

If it still not shows then add LSApplicationQueriesSchemes in info.plist file of array, add its item0 as instagram.

Replace

- (NSString*)urlencodedString:(NSString *)message{
return [message stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
}

With

- (NSString*)urlencodedString:(NSString *)message{
return [message stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];
}

This worked for me!

swift 3 get the latest Identifier simple and fast

  var lastIdentifier = ""
  let fetchOptions = PHFetchOptions()
  fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending:false)]
  let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions)
  if let lastAsset: PHAsset = fetchResult.lastObject {
    lastIdentifier = lastAsset.localIdentifier
  }

Here is code for sharing video on instagram : May be you need to add condition for substringFromIndex but its working.

 - (void)ShareAssetURLvideoToInstagram:(NSURL*)assetsLibraryURL
        {
            NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];

            NSString *strParamater = [assetsLibraryURL.absoluteString substringFromIndex:[assetsLibraryURL.absoluteString rangeOfString:@"?"].location+1];
            NSArray *urlComponents = [strParamater componentsSeparatedByString:@"&"];
            for (NSString *keyValuePair in urlComponents)
            {
                NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
                NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
                NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];

                [queryStringDictionary setObject:value forKey:key];
            }

            NSString *mediaId = [queryStringDictionary valueForKey:@"id"];

            if (mediaId.length > 0) {
                NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?LocalIdentifier=%@",mediaId]];

                if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
                    [[UIApplication sharedApplication] openURL:instagramURL];
                }
            }

        }
tk.duy
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
NSLog(@"Open Instagram!!"); //enter code here
[[UIApplication sharedApplication/*<enter your code here>*/] openURL:instagramURL];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!