How do you show a dialog when sharing a video with the FBSDK?
Here's how I got it to work. There's a particular URL format that FB requires.
if let lastAsset = fetchResult.firstObject {
let localID = lastAsset.localIdentifier
let assetID = localID.replacingOccurrences(of: "/.*", with: "", options: NSString.CompareOptions.regularExpression, range: nil)
let ext = "mp4"
let assetURLStr = "assets-library://asset/asset.\(ext)?id=\(assetID)&ext=\(ext)"
let video = FBSDKShareVideo(videoURL: URL(string: assetURLStr))
let content = FBSDKShareVideoContent()
content.video = video
let dialog = FBSDKShareDialog()
dialog.delegate = self
dialog.shareContent = content
dialog.shouldFailOnDataError = true
dialog.mode = .automatic
dialog.fromViewController = self
dialog.show()
}
This uses the other approach with ShareDialog() instead of FBSDKShareDialog()
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let fetchResult = PHAsset.fetchAssets(with: .video, options: fetchOptions)
if let lastAsset = fetchResult.firstObject {
let localID = lastAsset.localIdentifier
let assetID = localID.replacingOccurrences(of: "/.*", with: "", options: NSString.CompareOptions.regularExpression, range: nil)
let ext = "mp4"
let assetURLStr = "assets-library://asset/asset.\(ext)?id=\(assetID)&ext=\(ext)"
let video = Video(url: URL(string: assetURLStr)!)
let content = VideoShareContent(video: video)
let dialog = ShareDialog(content: content)
dialog.failsOnInvalidData = true
dialog.mode = .automatic
dialog.presentingViewController = self
do {
try dialog.show()
} catch {
print(error)
}
}
Sharing Video to facebook via FB SDK for iOS
You need to create something yourself or search for an existing solution on github (or similar). Something like a custom alert view where you can allow the user to enter text, have a thumbnail of the video which plays when tapped and a couple of buttons.
upload video to facebook using facebook sdk 3.1 on ios 6.0
Context
Before you can publish onto Facebook, you must get publish (write) permissions, using either native integration or the Facebook SDK, the rule is you must first acquire read permissions before write permissions.
Thus, make sure that before you attempt to upload a video, you should have requested basic info (email for example), then, once you have this, you can request write permissions. The permission necessary for uploading videos is publish_stream
.
Using iOS 6 native Facebook integration
Using the native iOS 6 Facebook integration, you should use the requestForServiceType:requestMethod:URL:parameters:
method of SLRequest
, as follows:
- (void)upload{
NSURL *videourl = [NSURL URLWithString:@"https://graph.facebook.com/me/videos"];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"me" ofType:@"mov"];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *params = @{
@"title": @"Me being silly",
@"description": @"Me testing the video upload to Facebook with the new system."
};
SLRequest *uploadRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:videourl
parameters:params];
[uploadRequest addMultipartData:videoData
withName:@"source"
type:@"video/quicktime"
filename:[pathURL absoluteString]];
uploadRequest.account = self.facebookAccount;
[uploadRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if(error){
NSLog(@"Error %@", error.localizedDescription);
}else
NSLog(@"%@", responseString);
}];
}
Here it's important to note that the video data does not go into the parameters dictionary, it must be added to the SLRequest
object using the addMultipartData:withName:type:filename:
method.
Also note that the filename is very important when adding the videos data. Here I am just using the full path of the file.
Using Facebook SDK 3.1 library
If you must support iOS versions earlier then iOS 6 or you wish to use the Facebook SDK 3.1 for any other reason, uploading a video is a little different.
You must use a FBRequest
object and a NSDictionary
that contains the videos details. The method I recommend using is requestWithGraphPath:parameters:HTTPMethod:
, I've used this method out of preference although you should be able to use some of the other methods to create your request object.
The following code works with Facebook SDK 3.1 to upload a video:
- (void)upload{
if (FBSession.activeSession.isOpen) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"me" 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);
}];
}
}
Here as you can see, we add the videos data into the parameters
dictionary unlike the previous solution, it's there along with title
and description
(which are 2 optional parameters).
Also note that here there is no key source
, as specified by the Facebook documentation.
The key's name is the filename of the video. I don't know why this shouldn't be source
, but using source results in a com.facebook.sdk error 5.
The bug I mentioned I filed with Facebook, you can see this report on this link - unless I'm mistaken in my interpretation of the documentation. Please try out that bug and report if you can reproduce it. Thanks !
How to convert a video NSURL to an ALAsset?
The documentation for an ALAsset states that
An ALAsset object represents a photo or a video managed by the Photo application.
so I'm pretty sure that you have to write the video to the camera roll before using it as an ALAsset. However, you don't need to open the camera roll and have a user pick the asset in order to use it. When writing to the ALAssetLibrary using
library.writeVideoAtPathToSavedPhotosAlbum(movieURL, completionBlock: { (newURL, error) -> Void
you get the asset url in that newUrl completion block variable. Use it in the Facebook sharing call
let content = FBSDKShareVideoContent()
content.video = FBSDKShareVideo(videoURL: newURL)
FBSDKShareAPI.shareWithContent(content, delegate: self)
NSLog("Facebook content shared \(content.video.videoURL)")
You can do this sharing inside the completion block if you so desire, or you can save the newUrl from the completion block and use it somewhere else.
Related Topics
iOS Check If Application Has Access to Microphone
Calculate All Permutations of a String in Swift
Selecting a Word in a Uitextview
Alamofire with a Self-Signed Certificate/Servertrustpolicy
Unarchive Array with Nskeyedunarchiver Unarchivedobject(Ofclass:From:)
iOS Autolayout and Uitoolbar/Uibarbuttonitems
How to Handle "Cfnetwork Sslhandshake Failed" in iOS
Is There Any Facebook Plugin for Phonegap 2.7.0
How to Force Uiviewcontroller Orientation
Cabasicanimation Rotate Returns to Original Position
Xcode Error While Validation - "Your Binary Is Not Optimized for iPhone 5"
Constant Movement in Spritekit
Uicontroleventtouchdragexit Triggers When 100 Pixels Away from Uibutton
How to Remove Border from Segmented Control
How to Add an Identifier to Auto Layout Constraints in Interface Builder
Nsnumberformatter with Comma Decimal Separator