2013-10-25 2 views
3

Я написал код, как показано ниже, где файл существует в ресурсах. Его значение не равно нулю.Как обмениваться видео в facebook SDK?

Мне удастся добавить изображения, но застрял в видео.

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

} 

В ответ я получаю сообщение об ошибке, как

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

Как загрузить видео на Facebook с помощью facebook IOS SDK?

Благодаря

+0

проверить рекомендованный формат видео FB. – user1673099

+0

откуда, вы можете передать ссылку только? – Duaan

+0

https://www.facebook.com/help/www/218673814818907 Они рекомендуют mp4. – opedge

ответ

0

Рекомендация:

Я думаю, что это может быть проблема с разрешениями, но я не уверен, где бросают ошибка. Метод делегирования, который будет выброшен, не отображается в вашем коде. Я думаю, что приведение в соответствие вашего кода с шагами в этом sample может оказаться полезным; если да, пожалуйста, примите ответ.

Некоторые ключевые аспекты выборки:

Разрешения:

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

Сложение Запрос:

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

Запрос метод didLoad делегат:

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

Запрос didFail метод делегата:

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

Facebook Видео Разрешения Link

-1

ли вы попросить publish_stream разрешения раньше?

+0

Это разрешение было заменено на 'publish_actions', пожалуйста Удалить ответ/вопрос. –

3

Вот способ загрузки видео на Facebook. Этот код тестируется и работает на 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]); 
    } 
}]; 
+1

Ни 'publ_stream', ни' video_upload' больше не существует. –

0

Этот код успешно протестирован на FaceBook SDK 3.14.1

Рекомендация: В .plist

множества FacebookAppID, FacebookDisplayName,
URL types-> Пункт 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); 
                     } 

                    }]; 
             } 
            }]; 
     } 
} 

И я получил ошибку:

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

Это происходит, когда facebook в настоящее время inited. В следующий раз, когда я открою свое приложение, он отлично работает, его всегда в первый раз. Пробовал все в приложении, но, похоже, это на стороне SDK для Facebook.

Несколько причин видеть com.facebook.sdk error 5:

  • сессия является не открыта. Подтвердить.
  • Facebook обнаружил, что вы спам системы. Измените имя видео.
  • Facebook имеет определенный предел, используя SDK. Попробуйте другое приложение.
Смежные вопросы