简体   繁体   English

如何在Facebook上传/分享视频?

[英]How to upload/share video on Facebook ?

I am making a test app through that I want to post video on facebook. 我正在制作一个测试应用程序,我想在Facebook上发布视频。 I am using latest sdk of facebook. 我正在使用Facebook最新的sdk。 But I am not able to post it on facebook. 但是我无法在Facebook上发布它。

My code is as below. 我的代码如下。

NSDictionary *parameters = [NSDictionary dictionaryWithObject:videoData forKey:@"CareAppDemo.mov"];

FBRequest *request = [FBRequest requestWithGraphPath:@"me/videos" parameters:parameters HTTPMethod:@"POST"];

[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                NSLog(@"result: %@, error: %@", result, error);
            }];

Please help me to post video on facebook via my app. 请帮我通过我的应用程序在Facebook上发布视频。

You need to download FacebookSDK first and then add following framework into your project 您需要先下载FacebookSDK,然后将以下框架添加到您的项目中

 FacebookSDK.framework, FBSDKLoginKit.framework, FBSDKShareKit.framework, Bolts.framework,FBSDKCoreKit.framework 

import them, and write followin code 导入它们,并编写以下代码

if(![FBSDKAccessToken currentAccessToken])
    {
        FBSDKLoginManager *login1 = [[FBSDKLoginManager alloc]init];

        [login1 logInWithPublishPermissions:@[@"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {

            FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];

            video.videoURL = videoAssetURL;
            FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
            content.video = video;

            [FBSDKShareDialog showFromViewController:self withContent:content delegate:nil];




        }];
    }
    else {
        FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
        video.videoURL = videoAssetURL;
        FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
        content.video = video;

        [FBSDKShareDialog showFromViewController:self withContent:content delegate:nil];




    }

The video URL videoURL must be an asset URL. 视频网址videoURL必须是资产网址。 You can get a video asset URL eg from UIImagePickerController. 您可以从UIImagePickerController获取视频资产URL。

or for recording video you can take as follow 或录制视频,您可以采取以下措施

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:[[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"] stringByAppendingFormat:@"/current.mov"]] completionBlock:^(NSURL *assetURL, NSError *error)
 {

     videoAssetURL =assetURL;

 }];

for more detail you can use https://developers.facebook.com/docs/sharing/ios 有关更多详细信息,请使用https://developers.facebook.com/docs/sharing/ios

Successfully tested On FaceBook SDK 3.14.1 FaceBook SDK 3.14.1上成功测试

Recommendation: 3 properties in .plist file 建议: .plist文件中的3个属性

set FacebookAppID,FacebookDisplayName, 设置FacebookAppID,FacebookDisplayName,
URL types->Item 0->URL Schemes set to facebookappId prefix with fb See URL类型 - >项目0-> URL方案设置为facebookappId前缀与fb 请参阅

-(void)shareOnFaceBook
{
    //sample_video.mov is the name of file
    NSString *filePathOfVideo = [[NSBundle mainBundle] pathForResource:@"sample_video" ofType:@"mov"];

    NSLog(@"Path  Of Video is %@", filePathOfVideo);
    NSData *videoData = [NSData dataWithContentsOfFile:filePathOfVideo];
    //you can use dataWithContentsOfURL if you have a Url of video file
    //NSData *videoData = [NSData dataWithContentsOfURL:shareURL];
    //NSLog(@"data is :%@",videoData);
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               videoData, @"video.mov",
                               @"video/quicktime", @"contentType",
                               @"Video name ", @"name",
                               @"description of Video", @"description",
                               nil];

   if (FBSession.activeSession.isOpen)
   {
        [FBRequestConnection startWithGraphPath:@"me/videos"
                                 parameters:params
                                 HTTPMethod:@"POST"
                          completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                              if(!error)
                              {
                                  NSLog(@"RESULT: %@", result);
                                  [self throwAlertWithTitle:@"Success" message:@"Video uploaded"];
                              }
                              else
                              {
                                  NSLog(@"ERROR: %@", error.localizedDescription);
                                  [self throwAlertWithTitle:@"Denied" message:@"Try Again"];
                              }
                          }];
    }
    else
    {
        NSArray *permissions = [[NSArray alloc] initWithObjects:
                            @"publish_actions",
                            nil];
        // OPEN Session!
        [FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone  allowLoginUI:YES
                                     completionHandler:^(FBSession *session,
                                                         FBSessionState status,
                                                         NSError *error) {
                                         if (error)
                                         {
                                             NSLog(@"Login fail :%@",error);
                                         }
                                         else if (FB_ISSESSIONOPENWITHSTATE(status))
                                         {
                                             [FBRequestConnection startWithGraphPath:@"me/videos"
                                                                          parameters:params
                                                                          HTTPMethod:@"POST"
                                                                   completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                                                       if(!error)
                                                                       {
                                                                           [self throwAlertWithTitle:@"Success" message:@"Video uploaded"];

                                                                           NSLog(@"RESULT: %@", result);
                                                                       }
                                                                       else
                                                                       {
                                                                           [self throwAlertWithTitle:@"Denied" message:@"Try Again"];

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

                                                                   }];
                                         }
                                     }];
        }
}

I GOT Error In first time of App runs: I GOT错误在App运行的第一次:

 The operation couldn’t be completed. (com.facebook.sdk error 5.)

It happens when facebook is being inited. 它发生在Facebook正在进行时。 Next time i open my app, it works fine, its always the first time. 下次我打开我的应用程序,它工作正常,它始终是第一次。 Tried everything in app, but it seems to be on the Facebook SDK side. 在应用程序中尝试了一切,但它似乎在Facebook SDK方面。

Few causes for seeing com.facebook.sdk error 5 : 看到com.facebook.sdk error 5原因很少:

  • Session is is not open. 会话未公开。 Validate. 验证。
  • Facebook has detected that you're spamming the system. Facebook已检测到您正在向系统发送垃圾邮件。 Change video name. 更改视频名称。
  • Facebook has a defined limit using the SDK. Facebook使用SDK有一个定义的限制。 Try a different app. 尝试使用其他应用。
  • Wrong publish permission. 错误的发布权限。 Give publish_actions a spin. publish_actions一个旋转。
  • many more.... 还有很多....

Best Example to upload video on Facebook Check it 在Facebook上传视频的最佳示例检查它

Download from below link that's only iPhone 从下面链接下载,这是唯一的iPhone

在此输入图像描述

Get the publish permission 获取发布权限

NSArray* permissions = [[NSArray alloc] initWithObjects:
                            @"publish_stream", nil];
    [facebook authorize:permissions delegate:self];
    [permissions release];

Try this 试试这个

- (void)fbDidLogin {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"mov"];
    NSData *videoData = [NSData dataWithContentsOfFile:filePath];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   videoData, @"video.mov",
                                   @"video/quicktime", @"contentType",
                                   @"Video Test Title", @"title",
                                   @"Video Test Description", @"description",
                       nil];
    [facebook requestWithGraphPath:@"me/videos"
                         andParams:params
                     andHttpMethod:@"POST"
                       andDelegate:self];
}

This is the old thread but for all the future readers coming, here is how to do it with the currently latest facebook SDK ( v3.24.0 - September 10th 2015 ). 这是旧线程,但对于所有未来的读者来说,这里是如何使用当前最新的facebook SDK( v3.24.0 - September 10th 2015 )。

- (IBAction)bntShareOnFacebookAction:(id)sender {

    if ([[FBSDKAccessToken currentAccessToken] hasGranted:@"publish_actions"]) {
        [self shareVideoOnFacebook];
    } else {
        FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
        [loginManager logOut];  //very important line for login to work
        [loginManager logInWithPublishPermissions:@[@"publish_actions"]
                handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
                        if(!error) {
                            [self shareVideoOnFacebook];
                        } 
                    }];
    }
}

- (void) shareVideoOnFacebook {

    NSString *videoPath = @"/Documents/.../movie.mov";
    NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:videoPath]];

    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:3L];

    [params setObject:videoData forKey:@"video_filename.MOV"];
    [params setObject:@"Title for this post." forKey:@"title"];
    [params setObject:@"Description for this post." forKey:@"description"];

    [[[FBSDKGraphRequest alloc] initWithGraphPath:@"/me/videos" parameters:params HTTPMethod:@"POST"]
     startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
         if (!error) {
             //video posted
         }
     }];
}

IF you want to Upload/Video sharing you must need to pass the Assets Library URL for the original version of the picked item. 如果您要上传/视频共享,则必须传递资产库URL以获取所选项目的原始版本。

URL e.g assets-library://asset/asset.MOV?id=18BC70A0-208A-4F03-A207-7D57C8863425&ext=MOV

If you are using 如果你正在使用

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 

Then you must need to pass 那你必须要通过

NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL];

If you using Document Directory Path then first you need to save video into library. 如果您使用文档目录路径,则首先需要将视频保存到库中。 You must need to create url link Assets Library URL. 您必须创建URL链接资产库URL。

[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

    [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoURL];

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

    if (success) {

        // Fetch Last saved video.
        PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
        fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:false]];

        // Get video url.
        PHAsset *fetchResult = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeVideo options:fetchOptions].firstObject;
        NSString *assetID = [fetchResult.localIdentifier substringToIndex:(fetchResult.localIdentifier.length - 7)];
        NSURL *assetURL = [NSURL URLWithString:[NSString stringWithFormat:@"assets-library://asset/asset.MOV?id=%@&ext=MOV", assetID]];

        // Share Video.
        FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
        video.videoURL = assetURL;

        FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
        content.video = video;

        FBSDKShareDialog *shareDialog = [[FBSDKShareDialog alloc] init];
        shareDialog.shareContent = content;
        shareDialog.delegate = (id)self;
        shareDialog.fromViewController = self;
        NSError * error = nil;
        BOOL validation = [shareDialog validateWithError:&error];
        if (validation) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [shareDialog show];
            });
        } else {
            NSLog(@"%@", error.localizedDescription);
        }

    }

}];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM