简体   繁体   English

如何在facebook SDK中分享视频?

[英]How to share video in facebook SDK?

I wrote code as below where file exists in resources. 我编写了如下代码,其中文件存在于资源中。 Its not null. 它不是空的。

I am successful in adding images, but stuck at videos. 我成功添加图像,但坚持视频。

-(void)uploadVideo {

    NSLog(@"UPload Videio ");

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"abc" ofType:@"mp4"];

    NSError *error = nil;


    NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];

    if(data == nil && error!=nil) {
        //Print error description

        NSLog(@"error is %@", [error description]);
    }

    NSLog(@"data is %@", data);

    NSDictionary *parameters = [NSDictionary dictionaryWithObject:data forKey:@"sample.mov"];

    if (FBSession.activeSession.isOpen) {


        [FBRequestConnection startWithGraphPath:@"me/videos"
                                     parameters:parameters
                                     HTTPMethod:@"POST"
                              completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                //  [FBRequestConnection setVideoMode:NO];

                                  if(!error) {
                                      NSLog(@"OK: %@", result);
                                  } else
                                      NSLog(@"Error: %@", error.localizedDescription);

                              }];

    } else {

        // We don't have an active session in this app, so lets open a new
        // facebook session with the appropriate permissions!

        // Firstly, construct a permission array.
        // you can find more "permissions strings" at http://developers.facebook.com/docs/authentication/permissions/
        // In this example, we will just request a publish_stream which is required to publish status or photos.

        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                @"publish_stream",
                                nil];
        //[self controlStatusUsable:NO];
        // OPEN Session!
        [FBSession openActiveSessionWithPermissions:permissions
                                       allowLoginUI:YES
                                  completionHandler:^(FBSession *session,
                                                      FBSessionState status,
                                                      NSError *error) {
                                      // if login fails for any reason, we alert
                                      if (error) {

                                          // show error to user.

                                      } else if (FB_ISSESSIONOPENWITHSTATE(status)) {

                                          // no error, so we proceed with requesting user details of current facebook session.


                                          [FBRequestConnection startWithGraphPath:@"me/videos"
                                                                       parameters:parameters
                                                                       HTTPMethod:@"POST"
                                                                completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                                                    //  [FBRequestConnection setVideoMode:NO];

                                                                    if(!error) {
                                                                        NSLog(@"Result: %@", result);
                                                                    } else
                                                                        NSLog(@"ERROR: %@", error.localizedDescription);

                                                                }];





                                          //[self promptUserWithAccountNameForUploadPhoto];
                                      }
                                      // [self controlStatusUsable:YES];
                                  }];
    }

}

In return I am getting error as 作为回报,我得到错误

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

How to upload video to facebook using facebook iOS SDK? 如何使用facebook iOS SDK将视频上传到Facebook?

Thanks 谢谢

Here's a method to upload video to Facebook. 这是将视频上传到Facebook的方法。 This code is testing and 100% working. 此代码正在测试并100%正常运行。

ACAccountStore *accountStore = [[ACAccountStore alloc] init];

ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

// Specify App ID and permissions
NSDictionary *options = @{ACFacebookAppIdKey: FACEBOOK_ID,
                          ACFacebookPermissionsKey: @[@"publish_stream", @"video_upload"],
                          ACFacebookAudienceKey: ACFacebookAudienceFriends}; // basic read permissions

[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *e) {
    if (granted) {
        NSArray *accountsArray = [accountStore accountsWithAccountType:facebookAccountType];

        if ([accountsArray count] > 0) {
            ACAccount *facebookAccount = [accountsArray objectAtIndex:0];


            NSDictionary *parameters = @{@"description": aMessage};


            SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
                                                            requestMethod:SLRequestMethodPOST
                                                                      URL:[NSURL URLWithString:@"https://graph.facebook.com/me/videos"]
                                                               parameters:parameters];

            [facebookRequest addMultipartData: aVideo
                                     withName:@"source"
                                         type:@"video/mp4"
                                     filename:@"video.mov"];

            facebookRequest.account = facebookAccount;


            [facebookRequest performRequestWithHandler:^(NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error) {
                if (error == nil) {
                    NSLog(@"responedata:%@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
                }else{
                    NSLog(@"%@",error.description);
                }
            }];
        }
    } else {
        NSLog(@"Access Denied");
        NSLog(@"[%@]",[e localizedDescription]);
    }
}];

Recommendation: 建议:

I think this might be a permissions issue but I am not sure where the error is being thrown. 我认为这可能是一个权限问题,但我不确定抛出错误的位置。 The delegate method that would be thrown is not shown in your code. 将抛出的委托方法未显示在您的代码中。 I think reconciling your code with the steps in this sample might be helpful; 我认为将您的代码与此示例中的步骤进行协调可能会有所帮助; if so please accept the answer. 如果是的话请接受答案。

Some key aspects of the sample: 样本的一些关键方面:

Permissions: 权限:

- (IBAction)buttonClicked:(id)sender {
    NSArray* permissions = [[NSArray alloc] initWithObjects:
                            @"publish_stream", nil];
    [facebook authorize:permissions delegate:self];
    [permissions release];
}

Build Request: 构建请求:

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

Request didLoad delegate method: 请求didLoad委托方法:

- (void)request:(FBRequest *)request didLoad:(id)result {
    if ([result isKindOfClass:[NSArray class]]) {
        result = [result objectAtIndex:0];
    }
    NSLog(@"Result of API call: %@", result);
}

Request didFail delegate method: 请求didFail委托方法:

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
    NSLog(@"Failed with error: %@", [error localizedDescription]);
}

Facebook Video Permissions Link Facebook视频权限链接

This Code is Tested successfully On FaceBook SDK 3.14.1 此代码在FaceBook SDK 3.14.1上成功测试

Recommendation: In .plist 建议:在.plist中

set FacebookAppID,FacebookDisplayName, 设置FacebookAppID,FacebookDisplayName,
URL types->Item 0->URL Schemes set to facebookappId prefix with fb URL类型 - >项目0-> URL方案设置为带有fb facebookappId前缀

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

                                                                   }];
                                         }
                                     }];
        }
}

And I GOT Error: 我GOT错误:

 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. 尝试使用其他应用。

您之前是否要求获得publish_stream权限?

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

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