使用挂钩在Instagram上发布视频

时间:2013-11-16 10:21:03

标签: ios objective-c video instagram

我希望我的应用能够将视频上传到Instagram。

Instagram IPhone Hooks提供有关如何使用iphone挂钩将照片上传到instagram的信息。我的问题是,如果有人有任何经验,如何完成相同但视频?

9 个答案:

答案 0 :(得分:44)

Instagram的API不直接支持从第三方应用程序上传任何内容。因此,在向用户提供功能时,您必须做出一些丑陋的用户体验妥协。

首先,准备要上传到Instagram的视频并将路径存储到某个地方

其次,将其保存到用户的相机胶卷:

if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(filePath)) {
    UISaveVideoAtPathToSavedPhotosAlbum(filePath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
}

第三,既然保存了视频,告诉用户为了将视频上传到Instagram,他们必须在点击上传按钮后从相机胶卷中选择它。

上传按钮只会执行以下操作:

NSURL *instagramURL = [NSURL URLWithString:@"instagram://camera"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
    [[UIApplication sharedApplication] openURL:instagramURL];
}

Instagram API不支持通过任何API端点立即选择媒体进行上传,这是非常愚蠢的,但就目前而言,这是唯一的方法。

答案 1 :(得分:20)

我有一个类似的问题:Instagram Video iPhone Hook我想出来了。有一个未记录的iPhone挂钩,允许您从iPhone照片卷自动选择资源,并预加载视频的标题。这应该为您提供Flipagrams应用程序与Instagram共享视频时的相同用户体验。

  

的Instagram://库AssetPath =资产库%3A%2F%2Fasset%2Fasset.mp4%3Fid%3D8864C466-A45C-4C48-B76F-E3C421711E9D%26ext%3Dmp4&安培; InstagramCaption =有些%20Preloaded%20Caption

NSURL *videoFilePath = ...; // Your local path to the video
NSString *caption = @"Some Preloaded Caption";
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:videoFilePath] completionBlock:^(NSURL *assetURL, NSError *error) {
    NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@",[assetURL absoluteString].percentEscape,caption.percentEscape]];
    if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
        [[UIApplication sharedApplication] openURL:instagramURL];
    }
}];

答案 2 :(得分:10)

尝试:

instagram://library?AssetPath=yourVideoPath

我在这里找到了解决方案:http://blog.horizon.camera/post/102273431070/video-share-objc-ios-instagram

答案 3 :(得分:5)

针对iOS 9进行了更新。

首先,对于iOS9,您需要添加到Info.plist文件中。添加值为LSApplicationQueriesSchemes的{​​{1}}密钥。这将使Instagram计划列入白名单。 More info here.

以下是基于johnnyg17&#39的工作代码:

instagram

样本instagramURL将是:

NSString *moviePath = @"<# /path/to/movie #>"; NSString *caption = @"<# Your caption #>"; NSURL *movieURL = [NSURL fileURLWithPath:moviePath isDirectory:NO]; ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeVideoAtPathToSavedPhotosAlbum:movieURL completionBlock:^(NSURL *assetURL, NSError *error) { NSURL *instagramURL = [NSURL URLWithString: [NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@", [[assetURL absoluteString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]], [caption stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]]] ]; if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) { [[UIApplication sharedApplication] openURL:instagramURL]; } else { NSLog(@"Can't open Instagram"); } }];

更新2016/5 :请注意,instagram://library?AssetPath=assets%2Dlibrary%3A%2F%2Fasset%2Fasset%2Emov%3Fid%3D69920271%2D2D44%2D4A84%2DA373%2D13602E8910B6%26ext%3Dmov&InstagramCaption=Super%20Selfie%20Dance%20%F0%9F%98%83现已弃用以保存到用户相册,现在推荐Photos Framework

答案 4 :(得分:2)

以下是Instagram上分享视频的快捷代码。

这里videoURL是视频的资产网址。

 func shareVideoToInstagram()
    {
        let videoURL : NSURL = "URL of video"

        let library = ALAssetsLibrary()
        library.writeVideoAtPathToSavedPhotosAlbum(videoURL) { (newURL, error) in

            let caption = "write your caption here..."

            let instagramString = "instagram://library?AssetPath=\((newURL.absoluteString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()))!)&InstagramCaption=\((caption.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()))!)"

            let instagramURL = NSURL(string: instagramString)

            if UIApplication.sharedApplication().canOpenURL(instagramURL!)
            {
                UIApplication.sharedApplication().openURL(instagramURL!)
            }
            else
            {
                print("Instagram app not installed.")
            }                
        }
    }

确保您在info.plist中添加了以下代码:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>instagram</string>
</array>

答案 5 :(得分:2)

Instagram已将此更新为使用较新的照片库。现在,您可以简单地传递相应的PHAsset的localIdentifier,而不是传递图像/视频网址:

PHAsset *first = /* Some PHAsset that you want to open Instagram to */;

NSURL *instagramURL = [NSURL URLWithString:[@"instagram://library?AssetPath=" stringByAppendingString:first.localIdentifier]];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
    [[UIApplication sharedApplication] openURL:instagramURL];
}

答案 6 :(得分:1)

Instagram API的上传功能非常有限,特别是在视频文件方面。

据我所知,在将媒体上传到Instagram时,您基本上有两种选择。您可以使用文档交互API将图像传递到Instagram应用程序,也可以调用Instagram相机并要求用户从他们的相机胶卷中进行选择(如Nico所述)。

我很确定你只能通过文档交互系统将JPEG或PNG文件传递给Instagram,所以对于视频我相信你现在一直坚持使用相机胶卷。这绝对不是理想的 - 我正在使用的应用程序现在使用iPhone挂钩,但我们决定坚持使用图像,直到Instagram改进他们的API。

答案 7 :(得分:0)

我使用了以下代码,它对我有用。

` [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            switch (status) {

                case PHAuthorizationStatusAuthorized: {

                    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"instagram://"]])
                    {
                            [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleExpand];
                            [MMProgressHUD showWithTitle:APPNAME status:@"Please wait..."];

                            _FinalVideoPath = [_FinalVideoPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

                            NSURL *videoUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@", _FinalVideoPath]];

                            dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
                            dispatch_async(q, ^{

                                NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];

                                dispatch_async(dispatch_get_main_queue(), ^{

                                    // Write it to cache directory
                                    NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.mov"];

                                    [videoData writeToFile:videoPath atomically:YES];

                                    [self createAlbumInPhotosLibrary:APPNAME videoAtFile:[NSURL fileURLWithPath:videoPath]ShareOnString:@"Instagram"];

                                });
                            });

                    }
                    else
                    {

                        [MMProgressHUD dismiss];

                        [STMethod showAlert:self Title:APPNAME Message:@"Please install Instagram to share this video" ButtonTitle:@"Ok"];
                    }

                    break;
                }

                case PHAuthorizationStatusRestricted: {
                    [self PhotosDenied];
                    break;
                }
                case PHAuthorizationStatusDenied: {

                    [self PhotosDenied];
                    break;
                }
                default:
                {
                    break;
                }
            }
        }];

- (void)createAlbumInPhotosLibrary:(NSString *)photoAlbumName videoAtFile:(NSURL *)videoURL ShareOnString:(NSString*)ShareOnStr
{

    // RELIVIT_moments
    __block PHFetchResult *photosAsset;
    __block PHAssetCollection *collection;
    __block PHObjectPlaceholder *placeholder;

    // Find the album
    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title = %@", photoAlbumName];
    collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
                                                          subtype:PHAssetCollectionSubtypeAny
                                                          options:fetchOptions].firstObject;
    // Create the album
    if (!collection)
    {
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetCollectionChangeRequest *createAlbum = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:photoAlbumName];
            placeholder = [createAlbum placeholderForCreatedAssetCollection];

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

            if (success)
            {
                PHFetchResult *collectionFetchResult = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[placeholder.localIdentifier]
                                                                                                            options:nil];
                collection = collectionFetchResult.firstObject;

                [self saveVideoInRelivitFolderSetPlaceHolder:placeholder photosAsset:photosAsset collection:collection VideoAtFile:videoURL ShareOnStr:ShareOnStr];

            }
            else
            {
                [MMProgressHUD dismiss];
            }

        }];

    } else {

        [self saveVideoInRelivitFolderSetPlaceHolder:placeholder photosAsset:photosAsset collection:collection VideoAtFile:videoURL ShareOnStr:ShareOnStr];
    }

}


- (void)saveVideoInRelivitFolderSetPlaceHolder:(PHObjectPlaceholder *)placeholderLocal photosAsset:(PHFetchResult *)photosAssetLocal  collection:(PHAssetCollection *)collectionLocal VideoAtFile:(NSURL *)videoURL ShareOnStr:(NSString*)ShareOnstring
{

    __block PHFetchResult *photosAsset = photosAssetLocal;
    __block PHAssetCollection *collection = collectionLocal;
    __block PHObjectPlaceholder *placeholder = placeholderLocal;

    // Save to the album
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoURL];
        placeholder = [assetRequest placeholderForCreatedAsset];
        photosAsset = [PHAsset fetchAssetsInAssetCollection:collection options:nil];

        PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection
                                                                                                                      assets:photosAsset];
        [albumChangeRequest addAssets:@[placeholder]];

    } completionHandler:^(BOOL success, NSError *error) {
        if (success)
        {
            NSLog(@"done");

            NSString *LocalIdentifire=placeholder.localIdentifier;

            NSString *AssetIdentifire=[LocalIdentifire stringByReplacingOccurrencesOfString:@"/.*" withString:@""];

            NSString *Extension=@"mov";

            NSString *AssetURL=[NSString stringWithFormat:@"assets-library://asset/asset.%@?id=%@&ext=%@",Extension,AssetIdentifire,Extension];

            NSURL *aSSurl=[NSURL URLWithString:AssetURL];

            [MMProgressHUD dismiss];

            if ([ShareOnstring isEqualToString:@"Instagram"])
            {
                NSLog(@"%@",AssetURL);

                NSString *caption = @"#Zoetrope";

                NSURL *instagramURL = [NSURL URLWithString:
                                       [NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@",
                                        [[aSSurl absoluteString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]],
                                        [caption stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]]]
                                       ];

                if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
                {
                    [MMProgressHUD dismiss];
                    [[UIApplication sharedApplication] openURL:instagramURL];
                }
                else
                {
                    NSLog(@"Can't open Instagram");
                    [MMProgressHUD dismiss];

                    [STMethod showAlert:self Title:APPNAME Message:@"Please install Instagram to share this video" ButtonTitle:@"Ok"];
                }

            }
             else
            {
                NSString *videoPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"file.mov"];

                NSError *removeError = nil;

                [[NSFileManager defaultManager] removeItemAtURL:[NSURL fileURLWithPath:videoPath] error:&removeError];

                NSLog(@"%@",[removeError localizedDescription]);

                ZShareSuccessViewController *ShareView=[self.storyboard instantiateViewControllerWithIdentifier:@"ZShareSuccessViewController"];

                [self.navigationController pushViewController:ShareView animated:true];

            }
        }
        else
        {

            if (![ShareOnstring isEqualToString:@"Instagram"] || [ShareOnstring isEqualToString:@"facebook"])
            {
                [self PhotosDenied];
            }

            [MMProgressHUD dismiss];

            NSLog(@"%@", error.localizedDescription);
        }
    }];

}


`

答案 8 :(得分:-3)

你可以通过媒体终点来完成

https://api.instagram.com/v1/media/3?access_token=ACCESS-TOKEN

获取有关媒体对象的信息。返回的类型键将允许您区分图像和视频媒体。

http://instagram.com/developer/endpoints/media/

此链接用于获取图片媒体ID。但我希望同样的技术可以在视频中提供帮助。

Where do I find the Instagram media ID of a image

NSURL *instagramURL = [NSURL URLWithString:@"instagram://media?id=315"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
    [[UIApplication sharedApplication] openURL:instagramURL];
}

优势信息:

  1. instagram://相机将打开相机或照片库(取决于设备),
  2. instagram://应用将打开应用
  3. instagram:// user?username = foo将打开该用户名
  4. instagram:// location?id = 1将打开该位置
  5. instagram:// media?id = 315将打开该媒体