我们可以使用Facebook SDK将文档目录视频上传到Facebook

时间:2015-05-26 11:07:15

标签: ios objective-c facebook-graph-api

我有一个问题是使用Facebook SDK将视频上传到Facebook。我正在尝试上传我从SavedPhotos中选择的视频工作正常。但是当我尝试从我的文档目录上传视频时,它会说下面的错误。 我所知道的是,我们可以上传具有资产网址的视频。有没有其他方法将文档目录视频上传到Facebook ???

错误是

 Array
(
    ["company] => 1
    [cat] => 3
    "
)

代码

2015-05-26 16:30:02.369 graphtwentysixth[3025:1413799] FB: ERROR=Error Domain=com.facebook.sdk.share Code=2 "The operation couldn’t be completed. (com.facebook.sdk.share error 2.)" UserInfo=0x156b0f90 {com.facebook.sdk:FBSDKErrorArgumentValueKey=file:///private/var/mobile/Containers/Bundle/Application/48DA75B3-63BA-400A-AC92-BE6B4A2B954B/graphtwentysixth.app/demo-video-high-quality.mov, com.facebook.sdk:FBSDKErrorArgumentNameKey=videoURL, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=Invalid value for videoURL: file:///private/var/mobile/Containers/Bundle/Application/48DA75B3-63BA-400A-AC92-BE6B4A2B954B/graphtwentysixth.app/demo-video-high-quality.mov}

感谢您宝贵的时间

4 个答案:

答案 0 :(得分:2)

无法从文档目录上传视频。你可以通过将视频作为资产来实现这一目标,而不是将资产的网址提供给Facebook,并在完成处理程序调用中从图库中删除该视频资产。这是一个技巧,但不是一个好的解决方案,因为当你将视频作为厨房的资产时,它将在savedPhotos中显示。

答案 1 :(得分:0)

像Shoaib所说,你需要先将视频转化为资产。请务必在班上加入#import <AssetsLibrary/AssetsLibrary.h>

    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    ALAssetsLibraryWriteVideoCompletionBlock videoWriteCompletionBlock = ^(NSURL *newURL, NSError *error) {
        if (error)
        {
            NSLog( @"Error writing image with metadata to Photo Library: %@", error );
        }
        else
        {
            NSLog(@"Wrote image with metadata to Photo Library %@", newURL.absoluteString);

            FBSDKShareVideo* video = [FBSDKShareVideo videoWithVideoURL:newURL];

            FBSDKShareVideoContent* content = [[FBSDKShareVideoContent alloc] init];
            content.video = video;

            [FBSDKShareAPI shareWithContent:content delegate:self];
        }
    };

    NSURL *videoURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"demo-video-high-quality" ofType:@"mov"]];

    if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:videoURL])
    {
        [library writeVideoAtPathToSavedPhotosAlbum:videoURL completionBlock:videoWriteCompletionBlock];
    }

(编辑的灵感部分来自this post

答案 2 :(得分:0)

您应首先将视频保存到资源库,然后获取正确的PHAsset并生成正确的网址:

guard let schemaUrl = URL(string: "fb://") else {
            return //be safe
}
if UIApplication.shared.canOpenURL(schemaUrl) {
    PHPhotoLibrary.requestAuthorization({ [weak self]
        (newStatus) in
        guard let strongSelf = self else {
            return
        }
        if newStatus ==  PHAuthorizationStatus.authorized {
            strongSelf.saveVideoToCameraRoll(url: assetURL, completion: { (result, phAsset) in
                phAsset?.getURL(completionHandler: { (url) in
                    if let url = url {
                        dispatchAsyncOnMainQueue {
                            let video = FBSDKShareVideo()
                            video.videoURL = url
                            let content = FBSDKShareVideoContent()
                            content.video = video
                            dialog.shareContent = content
                            dialog.show()
                        }
                    }
                })
            })                        
        } else {
            //unauthorized
        }
    })
} else {
    //facebookAppNotInstalled
}


...

func saveVideoToCameraRoll(url: URL, completion:@escaping (Bool, PHAsset?) -> ()) {
    PHPhotoLibrary.shared().performChanges({
        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
    }) { saved, error in
        if saved {
            let fetchOptions = PHFetchOptions()
            fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
            fetchOptions.fetchLimit = 1
            let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions).firstObject
            completion(true, fetchResult)
        } else {
            completion(false, nil)
        }
    }
}

...

extension PHAsset {    
    func getURL(completionHandler : @escaping ((_ responseURL : URL?) -> Void)){
         if self.mediaType == .video {
            let options: PHVideoRequestOptions = PHVideoRequestOptions()
            options.version = .original
            let nameParts = self.localIdentifier.components(separatedBy: "/")
            if nameParts.count > 0 {
                let assetFormatString = "assets-library://asset/asset.MP4?id=%@&ext=MP4"

                let name = nameParts[0]
                let urlString = String(format: assetFormatString, name)
                if let url = URL(string: urlString) {
                    completionHandler(url)
                } else {
                    completionHandler(nil)                    
                }
            }

        }
    }
}

答案 3 :(得分:-1)

您只需尝试以下代码,可以为您提供帮助。

- (void)upload{
    if (FBSession.activeSession.isOpen) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"demo-video-high-quality" 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);
        }];
    }
}