上下文
在您可以发布到 Facebook 之前,您必须获得发布(写入)权限,使用本机集成或 Facebook SDK,规则是您必须先获得读取权限,然后再获得写入权限。
因此,请确保在您尝试上传视频之前,您应该已请求基本信息(例如电子邮件),然后,一旦您拥有此信息,您就可以请求写入权限。上传视频所需的权限是publish_stream。
使用 iOS 6 原生 Facebook 集成
使用原生 iOS 6 Facebook 集成,您应该使用 requestForServiceType:requestMethod:URL:parameters:
SLRequest的方法,如下:
- (void)upload{
NSURL *videourl = [NSURL URLWithString:@"https://graph.facebook.com/me/videos"];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"me" ofType:@"mov"];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *params = @{
@"title": @"Me being silly",
@"description": @"Me testing the video upload to Facebook with the new system."
};
SLRequest *uploadRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:videourl
parameters:params];
[uploadRequest addMultipartData:videoData
withName:@"source"
type:@"video/quicktime"
filename:[pathURL absoluteString]];
uploadRequest.account = self.facebookAccount;
[uploadRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if(error){
NSLog(@"Error %@", error.localizedDescription);
}else
NSLog(@"%@", responseString);
}];
}
这里需要注意的是视频数据不进入参数字典,必须使用addMultipartData:withName:type:filename:方法添加到SLRequest对象中。
另请注意,添加视频数据时文件名非常重要。这里我只是使用文件的完整路径。
使用 Facebook SDK 3.1 库
如果您必须支持比 iOS 6 更早的 iOS 版本,或者您出于任何其他原因希望使用 Facebook SDK 3.1,则上传视频略有不同。
您必须使用 FBRequest 对象和包含视频详细信息的 NSDictionary。我推荐使用的方法是requestWithGraphPath:parameters:HTTPMethod:,尽管您应该能够使用其他一些方法来创建您的请求对象,但我还是出于偏好使用了此方法。
以下代码使用 Facebook SDK 3.1 上传视频:
- (void)upload{
if (FBSession.activeSession.isOpen) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"me" ofType:@"mov"];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *videoObject = @{
@"title": @"FB SDK 3.1",
@"description": @"hello there !",
[pathURL absoluteString]: videoData
};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:@"me/videos"
parameters:videoObject
HTTPMethod:@"POST"];
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
NSLog(@"Done: %@", result);
else
NSLog(@"Error: %@", error.localizedDescription);
}];
}
}
如您所见,我们将视频数据添加到parameters 字典中,与之前的解决方案不同,它与title 和description(这是两个可选参数)一起存在。
另请注意,这里没有 Facebook 文档指定的密钥 source。
密钥的名称是视频的文件名。我不知道为什么这不应该是source,但是使用源会导致 com.facebook.sdk 错误 5。
我提到的错误是我向 Facebook 提交的,您可以在 this link 上查看此报告 - 除非我对文档的解释有误。如果您可以重现它,请尝试该错误并报告。谢谢!