ios 使用钩子在 Instagram 上发布视频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20017266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:23:56  来源:igfitidea点击:

Posting video on instagram using hooks

iosobjective-cvideoinstagram

提问by Nilsymbol

I want my app to be able to upload videos to instagram.

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

Instagram IPhone Hooksgives information how to use the iphone hooks to upload a photo to instagram. My question is if anyone has any experience on how to accomplish the same but for a video?

Instagram iPhone Hooks提供了如何使用iPhone Hooks将照片上传到Instagram 的信息。我的问题是是否有人有任何关于如何完成相同但视频的经验?

回答by Nico H?m?l?inen

Instagram's API doesn't directly support uploading anything from 3rd party applications. Therefore you have to do some ugly user experience compromises when providing the functionality to your users.

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

First, Prepare the video you want to upload to Instagram and store the path to it somewhere

首先,准备要上传到 Instagram 的视频并将其路径存储在某处

Second, Save it to the user's Camera Roll:

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

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

Third, now that the video is saved, tell the user that in order to upload the video to their Instagram, they must select it from their camera roll after clicking the upload button.

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

The upload button would simply do the following:

上传按钮将简单地执行以下操作:

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

It's very silly that the Instagram API doesn't support immediate media selection through any of the API endpoints for upload purposes, but as it stands right now, this is the only way.

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

回答by johnnyg17

I had a similar question: Instagram Video iPhone Hookand I figured it out. There is an undocumented iPhone hook that allows you to automatically select assets from the iPhones photo roll, and preload a caption for the video. This should give you the same user experience that Flipagrams app has with sharing a video to Instagram.

我有一个类似的问题:Instagram Video iPhone Hook,我想通了。有一个未公开的 iPhone 挂钩,可让您自动从 iPhone 照片胶卷中选择资产,并为视频预加载标题。这应该为您提供与 Flipagrams 应用程序相同的用户体验,将视频分享到 Instagram。

instagram://library?AssetPath=assets-library%3A%2F%2Fasset%2Fasset.mp4%3Fid%3D8864C466-A45C-4C48-B76F-E3C421711E9D%26ext%3Dmp4&InstagramCaption=Some%20Preloaded%20Caption

instagram://library?AssetPath=assets-library%3A%2F%2Fasset%2Fasset.mp4%3Fid%3D8864C466-A45C-4C48-B76F-E3C421711E9D%26ext%3Dmp4&InstagramCaption=Some%20

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

回答by user1755548

try with:

尝试:

instagram://library?AssetPath=yourVideoPath

i found the solution here: http://blog.horizon.camera/post/102273431070/video-share-objc-ios-instagram

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

回答by Stan James

Updated for iOS 9.

针对 iOS 9 更新。

First, for iOS9 you'll need to add to your Info.plistfile. Add a key a LSApplicationQueriesSchemeswith the value instagram. This will whitelist the Instagram scheme. More info here.

首先,对于 iOS9,您需要添加到您的Info.plist文件中。添加一个LSApplicationQueriesSchemes值为a 的键instagram。这会将 Instagram 计划列入白名单。更多信息在这里。

Here is working code based on johnnyg17's:

这是基于 johnnyg17 的工作代码:

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

A sample instagramURL would be:

示例 instagramURL 将是:

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

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

Update 2016/5:Note that ALAssetsLibraryis now deprecated for saving to users photo album, and the Photos Frameworkis now reccomended.

2016/5 更新:请注意,ALAssetsLibrary现在不推荐使用它来保存到用户相册,现在推荐使用照片框架

回答by Adnan T.

Here is swift code for share video on Instagram.

这是在 Instagram 上分享视频的 swift 代码。

here videoURL is asset url of video.

这里 videoURL 是视频的资产 url。

 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.")
            }                
        }
    }

Make sure that you have added below code in info.plist:

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

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

回答by Tim

Instagram has updated this to use the newer Photos Library. Now, instead of passing the image/videos URL, you can simply pass the corresponding PHAsset's localIdentifier:

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

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

回答by David Schwartz

The Instagram API is extremely limited in its upload functionality, particularly when it comes to video files.

Instagram API 的上传功能极其有限,尤其是在视频文件方面。

From what I understand, you basically have two options when it comes to uploading media to Instagram. You can either use the Document Interaction API to pass an image over to the Instagram app, or you can call up the Instagram camera and ask the user to choose from their camera roll (as Nicosaid).

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

I'm pretty sure you can only pass JPEG or PNG files to Instagram through the Document Interaction system, so for video I believe you're stuck with the camera roll for now. It's definitely not ideal - the app I'm working on right now uses iPhone hooks, but we've decided to stick with images until Instagram improves their API.

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

回答by Jignesh Radadiya

I have used below code and it's working for me.

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

` [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);
        }
    }];

}


`

回答by codercat

you can done by media end point

您可以通过媒体端点完成

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

Get information about a media object. The returned type key will allow you to differentiate between image and video media.

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

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

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

Here this link is for get image media id. but i hope same technique will have help in video.

此链接用于获取图像媒体 ID。但我希望同样的技术对视频有所帮助。

Where do I find the Instagram media ID of a image

在哪里可以找到图片的 Instagram 媒体 ID

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

Advantage info:

优势信息:

  1. instagram://camera will open the camera or photo library (depending on device),
  2. instagram://app will open the app
  3. instagram://user?username=foo will open that username
  4. instagram://location?id=1 will open that location
  5. instagram://media?id=315 will open that media
  1. instagram://camera 将打开相机或照片库(取决于设备),
  2. instagram://app 将打开应用程序
  3. instagram://user?username=foo 将打开该用户名
  4. instagram://location?id=1 将打开该位置
  5. instagram://media?id=315 将打开该媒体