Подтвердить что ты не робот

Проводка видео на instagram с помощью крючков

Я хочу, чтобы мое приложение могло загружать видео в instagram.

Instagram IPhone Hooks дает информацию о том, как использовать крючки iphone для загрузки фотографии в instagram. Мой вопрос: есть ли у кого-нибудь опыт в том, как сделать то же самое, но для видео?

4b9b3361

Ответ 1

API Instagram напрямую не поддерживает загрузку файлов из сторонних приложений. Поэтому при выполнении функций пользователям необходимо выполнить некоторые уродливые компрометации пользователей.

Сначала подготовьте видео, которое вы хотите загрузить в Instagram, и сохраните путь к нему где-нибудь

Во-вторых, сохраните его для пользователя Camera Roll:

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

Очень глупо, что API-интерфейс Instagram не поддерживает немедленный выбор мультимедиа через любую из конечных точек API для загрузки, но поскольку он стоит прямо сейчас, это единственный способ.

Ответ 2

У меня был аналогичный вопрос: Instagram Video iPhone Hook, и я понял это. Существует недокументированный iPhone-крючок, который позволяет вам автоматически выбирать активы из фото-ролика iPhones и предварительно загружать заголовок для видео. Это должно дать вам тот же пользовательский интерфейс, что и приложение 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];
    }
}];

Ответ 4

Обновлен для iOS 9.

Во-первых, для iOS9 вам нужно добавить файл Info.plist. Добавьте ключ a LSApplicationQueriesSchemes со значением instagram. Это приведет к изменению списка Instagram. Подробнее здесь.

Вот рабочий код на основе johnnyg17's:

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

Пример 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

Обновление 2016/5: Обратите внимание, что ALAssetsLibrary теперь не рекомендуется для сохранения в фотоальбоме пользователей, а Photos Framework теперь рекомендуется.

Ответ 5

Instagram обновил это, чтобы использовать новую библиотеку фотографий. Теперь вместо передачи URL изображения/видео вы можете просто передать соответствующий локальный идентификатор PHAsset:

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

API-интерфейс Instagram чрезвычайно ограничен в своих функциях загрузки, особенно когда речь заходит о видеофайлах.

Из того, что я понимаю, у вас в основном есть два варианта, когда дело доходит до загрузки медиафайлов в Instagram. Вы можете использовать API взаимодействия документов, чтобы передать изображение в приложение Instagram, или вы можете вызвать камеру Instagram и попросить пользователя выбрать из своего рулона камеры (в качестве Nico said).

Я уверен, что вы можете передавать файлы JPEG или PNG только в Instagram через систему взаимодействия с документами, поэтому для видео я полагаю, что вы застряли в показе камеры. Это определенно не идеально - приложение, над которым я сейчас работаю, использует iPhone-крючки, но мы решили использовать изображения, пока Instagram не улучшит их API.

Ответ 7

Вот быстрый код для совместного использования видео на Instagram.

здесь 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.")
            }                
        }
    }

Убедитесь, что вы добавили код ниже в info.plist:

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

Ответ 8

Я использовал ниже код, и он работает для меня.

` [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 *[email protected]"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);
        }
    }];

}


`

Ответ 9

вы можете сделать с помощью конечной точки мультимедиа

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

Получить информацию о медиа-объекте. Возвращенный тип ключа позволит вам различать изображение и видео.

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

Здесь эта ссылка предназначена для получения идентификатора носителя изображения. но я надеюсь, что одна и та же техника поможет в видео.

Где найти идентификатор носителя Instagram изображения

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

Информация о преимуществах:

  • instagram://камера откроет камеру или библиотеку фотографий (в зависимости от устройства),
  • instagram://приложение откроет приложение
  • instagram://user? username = foo откроет это имя пользователя
  • instagram://location? id = 1 откроет это местоположение
  • instagram://media? id = 315 откроет этот носитель