1

I have a question in uploading the video to Facebook using Facebook SDK.I am trying to upload the video which I have selected from SavedPhotos is working fine. But When I am trying to upload the video from my documents directory it is saying this below error. What I know is we can upload the video which are having the asset url. Is there any other way to upload the documents directory video to the facebook???

Error is

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}

Code

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

FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = videoURL;
FBSDKShareVideoContent *content1 = [[FBSDKShareVideoContent alloc] init];
content1.video = video;
[FBSDKShareAPI shareWithContent:content1 delegate:self];

Thank you for your valuable time

SRI
  • 1,514
  • 21
  • 39

4 Answers4

2

The video cannot be uploaded from document directory. You can achieve this by making video an asset and than give the url of asset to Facebook and on completion handler call delete that video asset from gallery. This is a trick but not a good solution as when you make video an asset of galley it will visible in savedPhotos.

Shoaib
  • 21
  • 3
  • Thank you for the idea but since last one hour I am trying to change that vodeo url to asset url. Could you help me out ?? – SRI May 26 '15 at 11:23
  • Yes you can use graph API to upload video from your directory but you need permission for graph API to post video on user's wall – Shoaib May 26 '15 at 11:35
  • You cannot make video url to asset ur directly, You need to copy that video into your asset library than pass that asset url to Facebook – Shoaib May 26 '15 at 11:43
  • You can't even use the graph API for uploading the video saved in the documents directory. See here and search for the section titled "Sharing photos and videos": https://developers.facebook.com/docs/ios/graph it looks like there's no way around the Asset issue. – user3344977 Jan 18 '16 at 21:26
0

Like Shoaib said, you'll need to make the video into an asset first. Be sure to include #import <AssetsLibrary/AssetsLibrary.h> in your class.

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

(EDIT inspired in part by this post)

Community
  • 1
  • 1
Olivia Stork
  • 4,660
  • 5
  • 27
  • 40
0

You should first save the video to your Library, then get the correct PHAsset and generate the correct URL:

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

        }
    }
}
Bisca
  • 6,380
  • 2
  • 19
  • 32
-1

You just try below code may it's help to you.

- (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);
        }];
    }
}
Nimit Parekh
  • 16,776
  • 8
  • 50
  • 72