使用SLRequest(无对话)将视频上传到ios 6中的Facebook的示例 [英] example of uploading video to facebook in ios 6 using SLRequest (without dialog)

查看:132
本文介绍了使用SLRequest(无对话)将视频上传到ios 6中的Facebook的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个例子,其中使用iOS 6& SLRequest。我已经有我的代码可以上传照片。



提前感谢

解决方案

将视频分享到FB:




  • 在developer.facebook.com上创建一个应用程序
  • $ b $在iOS平台上的app应用程序页面的develper.facebook.com中提到appName-info.plist中的AppId
  • 提交应用程序BundleID



然后编码:



我们必须申请读权限,然后写权限。

   - (void)shareOnFB 
{
__block ACAccount * facebookAccount;
ACAccountStore * accountStore = [[ACAccountStore alloc] init];
NSDictionary * emailReadPermisson = [[NSDictionary alloc] initWithObjectsAndKeys:
FB_APP_ID,ACFacebookAppIdKey,
@ [@email],ACFacebookPermissionsKey,
ACFacebookAudienceFriends,ACFacebookAudienceKey,
nil ]。

NSDictionary * publishWritePermisson = [[NSDictionary alloc] initWithObjectsAndKeys:
FB_APP_ID,ACFacebookAppIdKey,
@ [@publish_stream],ACFacebookPermissionsKey,
ACFacebookAudienceFriends,ACFacebookAudienceKey,
nil];

ACAccountType * facebookAccountType = [accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
//请求读取权限

[accountStore requestAccessToAccountsWithType:facebookAccountType选项:emailReadPermisson完成:^(BOOL授予,NSError *错误){

if(授予)
{
//请求写入权限
[accountStore requestAccessToAccountsWithType:facebookAccountType选项:publishWritePermisson完成:^(BOOL授予,NSError *错误){

if(授予)
{
NSArray * accounts = [accountStore
accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
NSLog(@访问Facebook帐户ok%@,facebookAccount.username);
[self uploadWithFBAccount:facebookAccount];
}
else
{
NSLog(@访问Facebook不被授予);
//如果需要,额外的处理
dispatch_async(dispatch_get_main_queue(),^ {
//正常失败...
NSLog(@%@,error.description) ;
[self errorMethodFromFB:error];
});
}
}];
}
else
{
[self errorMethodFromFB:error];
}
}];
}

然后从Facebook处理错误方法

   - (void)errorMethodFromFB :( NSError *)错误
{

NSLog(@访问Facebook不被授予 );
//如果需要,额外处理

dispatch_async(dispatch_get_main_queue(),^ {

//正常失败...
NSLog(@ %@,error.description);

if([错误代码] == ACErrorAccountNotFound)
[self throwAlertWithTitle:@错误消息:@找不到帐户请设置您的帐户在设置应用程序];
如果([错误代码] == ACErrorAccessInfoInvalid)
[self throwAlertWithTitle:@错误消息:@客户端的访问信息字典有不正确或缺失的值。 ];
if([error code] == ACErrorPermissionDenied)
[self throwAlertWithTitle:@Errormessage:@操作未完成,因为用户拒绝了权限。];
else
[self throwAlertWithTitle:@Errormessage:@Account access denied。];
});
}

然后消息警报



< (NSString *)标题消息:(NSString *)msg
{
[[UIAlertView alloc] initWithTitle:标题消息:msg委托:nil cancelButtonTitle:@OKotherButtonTitles:nil,nil] show];
}

处理上传方法

   - (void)uploadWithFBAccount:(ACAccount *)facebookAccount 
{
ACAccountCredential * fbCredential = [facebookAccount credential];
NSString * accessToken = [fbCredential oauthToken];

NSURL * videourl = [NSURL URLWithString:[NSString stringWithFormat:@https://graph.facebook.com/me/videos?access_token=%@,accessToken]];

NSFileManager * fileManager = [NSFileManager defaultManager];

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * foofile = [documentsDirectory stringByAppendingPathComponent:@me.mov];
BOOL fileExists = [fileManager fileExistsAtPath:foofile];
if(fileExists)
{
NSLog(@file saved);
}
NSString * filePath = foofile;
NSURL * pathURL = [[NSURL alloc] initFileURLWithPath:filePath isDirectory:NO];
NSData * videoData = [NSData dataWithContentsOfFile:filePath];
NSDictionary * params = @ {
@title:@我傻,
@description:@我用新的社交框架测试视频上传到Facebook。
};

SLRequest * uploadRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:videourl
参数:params];
[uploadRequest addMultipartData:videoData
withName:@source
type:@video / quicktime
filename:[pathURL absoluteString]];

uploadRequest.account = facebookAccount;

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^(void){
[uploadRequest performRequestWithHandler:^(NSData * responseData,NSHTTPURLResponse * urlResponse,NSError * error){
NSDictionary * responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData选项:NSJSONReadingMutableContainers错误:& error];
NSString * responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

if(error )
{
NSLog(@Error%@,error.localizedDescription);
}
else
{
[[[UIAlertView alloc] initWithTitle :@恭喜!消息:@你的视频被自动发布到你的FB newsfeed委托:nil cancelButtonTitle:@OKotherButtonTitles:nil,nil] show];
NSLog(@%@ responseString);
}
}];
});
}


I am looking for an example where a video is posted to facebook using iOS 6 & SLRequest. I already have my code working for uploading a photo.

Thanks in advance!

解决方案

For sharing a Video to FB :

  • Create an app on developer.facebook.com
  • mention the AppId in appName-info.plist
  • mention app BundleID in develper.facebook.com of your app page under iOS platform

Then on coding:

we have to request for read permission then write permission .

-(void)shareOnFB
{
      __block ACAccount * facebookAccount;
      ACAccountStore *accountStore = [[ACAccountStore alloc] init];
      NSDictionary *emailReadPermisson = [[NSDictionary alloc] initWithObjectsAndKeys:
                                    FB_APP_ID,ACFacebookAppIdKey,
                                    @[@"email"],ACFacebookPermissionsKey,
                                    ACFacebookAudienceFriends,ACFacebookAudienceKey,
                                    nil];

      NSDictionary *publishWritePermisson = [[NSDictionary alloc] initWithObjectsAndKeys:
                                       FB_APP_ID,ACFacebookAppIdKey,
                                       @[@"publish_stream"],ACFacebookPermissionsKey,
                                       ACFacebookAudienceFriends,ACFacebookAudienceKey,
                                       nil];

     ACAccountType *facebookAccountType = [accountStore
                                      accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
      //Request for Read permission

    [accountStore requestAccessToAccountsWithType:facebookAccountType options:emailReadPermisson completion:^(BOOL granted, NSError *error) {

    if (granted)
    {
        //Request for write permission
        [accountStore requestAccessToAccountsWithType:facebookAccountType options:publishWritePermisson completion:^(BOOL granted, NSError *error) {

        if (granted)
        {
             NSArray *accounts = [accountStore
                                     accountsWithAccountType:facebookAccountType];
             facebookAccount = [accounts lastObject];
             NSLog(@"access to facebook account ok %@", facebookAccount.username);
             [self uploadWithFBAccount:facebookAccount];
        } 
        else 
        {
             NSLog(@"access to facebook is not granted");
               // extra handling here if necesary
             dispatch_async(dispatch_get_main_queue(), ^{
                 // Fail gracefully...
                NSLog(@"%@",error.description);
                [self errorMethodFromFB:error];
                });
         }
      }];
    }
    else
    {
       [self errorMethodFromFB:error];
    }
  }];
}

Then Handle the error method from facebook

-(void)errorMethodFromFB:(NSError *)error
{

    NSLog(@"access to facebook is not granted");
   // extra handling here if necesary

  dispatch_async(dispatch_get_main_queue(), ^{

      // Fail gracefully...
      NSLog(@"%@",error.description);

      if([error code]== ACErrorAccountNotFound)
          [self throwAlertWithTitle:@"Error" message:@"Account not found. Please setup your account in settings app."];
      if ([error code] == ACErrorAccessInfoInvalid)
          [self throwAlertWithTitle:@"Error" message:@"The client's access info dictionary has incorrect or missing values."];
     if ([error code] ==  ACErrorPermissionDenied)
          [self throwAlertWithTitle:@"Error" message:@"The operation didn't complete because the user denied permission."];
     else
          [self throwAlertWithTitle:@"Error" message:@"Account access denied."];
  });
}

Then message alert

-(void)throwAlertWithTitle:(NSString *)title message:(NSString *)msg
{
     [[[UIAlertView alloc]initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]show];
}

Handle Uploading method

-(void)uploadWithFBAccount:(ACAccount *)facebookAccount
{
    ACAccountCredential *fbCredential = [facebookAccount credential];
    NSString *accessToken = [fbCredential oauthToken];

    NSURL *videourl = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/me/videos?access_token=%@",accessToken]];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* foofile = [documentsDirectory stringByAppendingPathComponent:@"me.mov"];
    BOOL fileExists = [fileManager fileExistsAtPath:foofile];
   if (fileExists) 
   {
       NSLog(@"file saved");
   }
   NSString *filePath = foofile;
   NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
   NSData *videoData = [NSData dataWithContentsOfFile:filePath];
   NSDictionary *params = @{
                         @"title": @"Me  silly",
                         @"description": @"Me testing the video upload to Facebook with the new Social Framework."
                         };

   SLRequest *uploadRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
                                              requestMethod:SLRequestMethodPOST
                                                        URL:videourl
                                                 parameters:params];
  [uploadRequest addMultipartData:videoData
                       withName:@"source"
                           type:@"video/quicktime"
                       filename:[pathURL absoluteString]];

    uploadRequest.account = facebookAccount;

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
        [uploadRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
            NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
            NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

           if(error)
           {
                 NSLog(@"Error %@", error.localizedDescription);
           }
           else
           {
                [[[UIAlertView alloc]initWithTitle:@"Congratulations!" message:@"Your video is suucessfully posted to your FB newsfeed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]show];
                NSLog(@"%@", responseString);
           }
       }];
   });
}

这篇关于使用SLRequest(无对话)将视频上传到ios 6中的Facebook的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆