2014-01-28 53 views
5

我正在製作一個測試應用程序,我希望在Facebook上發佈視頻。我正在使用Facebook的最新sdk。但我無法在Facebook上發佈。如何在Facebook上上傳/分享視頻?

我的代碼如下。

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

請幫我張貼在Facebook上的視頻通過我的應用程序。

+0

看到圖片並從那裏下載。你只能在其中設置facebook appid。 –

回答

1

最好的例子,從上傳的視頻在Facebook上Check it

下載下面的鏈接只有iPhone的

enter image description here

+0

告訴我如何在iPhone模擬器中運行此代碼? – Hitendra

1

獲得發佈許可

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]; 
} 
+0

我使用了這段代碼。但沒有工作。我得到了這個錯誤的錯誤:錯誤域= facebookErrDomain代碼= 10000「該操作無法完成。(facebookErrDomain錯誤10000.)」UserInfo = 0x758a250 {error = { code = 100; message =「來自服務器的API調用需要一個appsecret_proof參數」; type = GraphMethodException; – Hitendra

+0

所以我的猜測是appsecret_proof的應用設置已啓用,但您沒有使用最新版本的iOS SDK,因此未生成appcesret_proof。 您可能想要在應用程序儀表板>設置>高級>安全性中檢查您的設置。 – Retro

4

試驗成功論FaceBook SDK 3.14.1

建議:在的.plist文件 3個屬性

集FacebookAppID,FacebookDisplayName,
URL類型 - >物品0-> URL方案設置爲facebookappId前綴fbSee

-(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.) 

被inited的Facebook時,它發生。下次我打開我的應用程序,它工作正常,它總是第一次。嘗試了應用程序中的所有內容,但似乎在Facebook SDK一側。

幾個原因看到com.facebook.sdk error 5

  • 會議是不開放的。驗證。
  • Facebook檢測到您發送垃圾郵件。更改視頻名稱。
  • Facebook使用SDK定義了一個限制。嘗試不同的應用程序。
  • 錯誤的發佈權限。給publish_actions一個旋轉。
  • 更多....
+0

這有效,但你有沒有想過如何解決第一次問題?我願意修復它,如果我可以。當您不從Facebook批准您的應用程序時,您需要使用 –

+1

。然後它會在第一次出錯。 經Facebook審批通過,成功運行。 –

+0

非常感謝您的提示。實際上,我通過在第一個調用之後嵌套另一個調用來結束編寫黑客的工作,所以如果您正在測試,則不會顯示錯誤。 –

5

您需要下載FacebookSDK第一 然後添加以下框架到您的項目

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

導入, 寫跟隨着代碼

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




    } 

視頻URL videoURL必須是資產網址。您可以獲取視頻資源網址,例如來自UIImagePickerController。

或錄製視頻,你可以採取如下

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

    videoAssetURL =assetURL; 

}]; 

更多的細節,你可以使用https://developers.facebook.com/docs/sharing/ios

+0

This Works。但不存在爲視頻添加標題和描述的方式。 – jose920405

+0

是的,有沒有辦法添加標題和描述,因爲,請參閱2.3節https://developers.facebook.com/policy。 但是我們可以在發佈之前給用戶另外一個選項。在剪貼板中複製描述文本(使用UIPasteboard)並向用戶顯示警告,例如「評論已複製到剪貼板以粘貼您的帖子」。在發佈視頻之前。 – jay

1

這是舊線,但對於所有未來的讀者來了,這裏是如何做到這一點與當前最新的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 
     } 
    }]; 
} 
+0

未添加預先填寫的說明是否違反了Facebook的政策? https://developers.facebook.com/docs/apps/review/prefill – Matt

+0

@Matt - 字段僅用於演示目的進行硬編碼,以使代碼更具可讀性。隨意從用戶輸入中提取該信息。 –

0

如果你想上傳/視頻共享你必須要通過資產庫網址爲挑選項目的原始版本。

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

如果您正在使用

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

那麼你一定需要通過

NSURL *url = [info objectForKey:UIImagePickerControllerReferenceURL]; 

如果您在使用文件目錄路徑那麼首先您需要保存視頻到庫中。您必須創建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); 
     } 

    } 

}];