Instagram hooks pre-select 媒体问题

Instagram hooks pre-select media issue

这是我的代码。文件已正确添加到照片库,但在 instagram 应用程序中 url -> instagram://library?AssetPath=assets-library%3A%2F%2Fasset%2Fasset.mp4%3Fid=5EDBD113-FF57-476B-AABB-6A59F31170B5&ext=mp4&InstagramCaption=my%caption 不要打开最后一个视频。

- (void)loadCameraRollAssetToInstagram:(NSURL*)assetsLibraryURL andMessage:(NSString*)message
{
    NSString *escapedString   = [self urlencodedString:assetsLibraryURL.absoluteString];
    NSString *escapedCaption  = [self urlencodedString:message];
    NSURL *instagramURL       = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@", escapedString, escapedCaption]];

    NSLog(@"instagramURL ==> %@",instagramURL);

    if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
        NSLog(@"Open Instagram!!");
        [[UIApplication sharedApplication] openURL:instagramURL];
    } else {
        NSLog(@"Cant open Instagram!!");
        [[[UIAlertView alloc] initWithTitle:@"Instagram" message:@"App not installed" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] show];
    }
}

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

- (void)saveToCameraRoll:(NSURL *)srcURL withCurrentAction:(NSString *)action
{
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    ALAssetsLibraryWriteVideoCompletionBlock videoWriteCompletionBlock = ^(NSURL *newURL, NSError *error) {

        if (error) {
            NSLog( @"Error writing image with metadata to Photo Library: %@", error );
            [[[UIAlertView alloc] initWithTitle:@"Facebook" message:@"Pal - Currently we can't process your video. Please try again in few moments" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Sign In", nil] show];

        } else {
            NSLog( @"Wrote image with metadata to Photo Library: %@", newURL.absoluteString);
            if ([action isEqualToString:@"instagram"])
                [self loadCameraRollAssetToInstagram:newURL andMessage:@"My caption"]; //Can be any text?
        }
    };

    if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:srcURL])
    {
        [library writeVideoAtPathToSavedPhotosAlbum:srcURL completionBlock:videoWriteCompletionBlock];
    }
}

非常奇怪的是它运行完美,直到我卸载然后安装 instagram。不知道这个有没有关系

if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
NSLog(@"Open Instagram!!"); //enter code here
[[UIApplication sharedApplication/*<enter your code here>*/] openURL:instagramURL];

使用此代码

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 将只显示那些保存在您在 instagramURL 中设置的路径的 iamges/videos。那条路应该是绝对的。

如果仍然没有显示,则在数组的info.plist文件中添加LSApplicationQueriesSchemes,将其item0添加为instagram。

替换

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

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

这对我有用!

instagram://library?AssetPath=\(assetsLibraryUrl) 前一段时间停止工作了。 Instagram 开发人员可能已转向 Photos 框架,不再使用 AssetsLibrary。

有了这个假设,我尝试了其他几个参数名称,发现 instagram://library?LocalIdentifier=\(localID) 其中 localIdPHAssetlocalIdentifier 目前可以使用。

这仍然是未记录的,因此它可能会在 Instagram 的任何未来版本中崩溃。

@borisgolovnev 的解决方案确实有效。您可以使用以下代码获取上次保存的视频的 localIdentifier。使用 instagram://library?LocalIdentifier=(localID) 传递它会打开 Instagram 并选择您的视频。

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
}

swift 3获取最新Identifier 简单快速

  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
  }

长时间后恢复此任务并考虑 borisgolovnev's 答案和 ALAssetsLibrary 已弃用,最终解决方案是:

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

别忘了

#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>

以下是在 Instagram 上分享视频的代码: 可能您需要为 substringFromIndex 添加条件,但它可以正常工作。

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

        }