将视频分享到 Facebook
Share a video to Facebook
我正在编写一个简单的测试应用程序,用于将视频从 iOS 上传到 Facebook。
我发现很难在网上找到 examples/tutorials 如何使用 Swift 执行此操作,因为 FacebookSDK 的所有文档都在 Objective-C.[=12= 中]
到目前为止,我有这个,它在我的 UI 上放置了一个共享按钮,但它看起来已禁用,据我所知,这是因为没有设置内容,但我看不出这是怎么可能的.
let video_content : FBSDKShareVideoContent = FBSDKShareVideoContent()
video_content.video = FBSDKShareVideo(videoURL: getVideoURL())
let button : FBSDKShareButton = FBSDKShareButton()
button.shareContent = video_content
button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 100) * 0.5, 50, 100, 25)
self.view.addSubview(button)
我的 getVideoURL()
函数 returns 一个肯定包含 url 到视频的 NSURL(我已经将它打印到控制台并检查它指向我存储在较早的文件夹)。
看了社交框架,可惜不能用,好像只能分享照片,不能分享视频。
我使用的是最新版本的 Xcode、Swift 和 Facebook SDK。
我在 objective c 中做过这个,我也遇到过类似的问题。不知道这是否适用于 swift.
问题是,如果出于某种原因,视频必须存储在 NSDocumentDirectory
或 NSTemporaryDirectory
中,这样她才能工作。不是你的情况。
虽然你可以在最坏的情况下使用 FBSDKGraphRequest
和 /me/Videos
我了解到您尝试使用的这种分享视频的方式,可以直接从照片库中获取链接。正如您在 this example
中看到的
目前在objective-c
中只有示例,希望对您有所帮助
- (void)uploadVideoWithoutSettingsCredentials:(NSURL *)videoUrl withTitle:(NSString *)title withDesc:(NSString *)desc withPrivacy:(NSString *)privacy
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^{
NSError * error = nil;
NSData * videoData = [NSData dataWithContentsOfURL:videoUrl options:0 error:&error];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:4L];
[params setObject:videoData forKey:[NSString stringWithFormat:@"%@.MOV",title]];
[params setObject:desc forKey:@"description"];
NSString *privacyString = @"EVERYONE";
if (privacy.length > 0)
privacyString = privacy;
NSDictionary *privacyDict = [[NSDictionary alloc] initWithObjectsAndKeys: privacyString, @"value", nil];
[params setObject:[Utils objectToJsonString:privacyDict] forKey:@"privacy"];
dispatch_async(dispatch_get_main_queue(), ^{
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"/me/videos" parameters:params HTTPMethod:@"POST"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(@"RESPONSE!!! /me/videos");
NSLog(@"result %@",result);
NSLog(@"error %@",error);
dispatch_async(dispatch_get_main_queue(), ^{
if (!error) {
[[[UIAlertView alloc] initWithTitle:@"Success" message:@"Your clip was posted!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];
} else {
[[[UIAlertView alloc] initWithTitle:@"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];
}
});
}];
});
});
}
您可以更改为 swift 语法,使用 Xcode 自动完成功能。
您可以使用语法 swift 和 this
来帮助自己
我在我的应用程序中使用了这段代码,对我来说效果很好。
此代码适用于 Objective-C,但您可以在将其转换为 swift 语法后在 swift 中使用相同的代码。
希望对您有所帮助。
尝试下面的代码。
-(void) uploadVideoOnFacebook
{
NSURL *pathURL;
NSData *videoData;
pathURL = [NSURL URLWithString:self.strUploadVideoURL];
videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.strUploadVideoURL]];
NSString *strDesc;
strDesc = txtCaption.text;
NSDictionary *videoObject = @{@"title": @"application Name",@"description": strDesc,[pathURL absoluteString]: videoData};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:@"me/videos" parameters:videoObject HTTPMethod:@"POST"];
[self.view setUserInteractionEnabled:NO];
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
NSLog("Success");
else
NSLog("Error");
}];
}
@AngryDuck
试试这个代码它会起作用
func uploadVideoOnFacebook() {
var pathURL: NSURL
var videoData: NSData
pathURL = NSURL(string: self.strUploadVideoURL)!
videoData = NSData.dataWithContentsOfURL(NSURL(string: self.strUploadVideoURL)!)
NSString * strDesc
strDesc = txtCaption.text!
var videoObject: [NSObject : AnyObject] = ["title": "application Name", "description": strDesc, pathURL.absoluteString(): videoData]
var uploadRequest: FBRequest = FBRequest(graphPath: "me/videos", parameters: videoObject, HTTPMethod: "POST")
self.view!.userInteractionEnabled = false
uploadRequest.startWithCompletionHandler({(connection: FBRequestConnection, result: AnyObject, error: NSError) -> Void in
if !error {
NSLog("Success")
}
else {
NSLog("Error")
}
})
}
转换成swift3和4:-
试试这个
func uploadVideoOnFacebook() {
var pathURL: URL
var videoData: Data
pathURL = URL(string: "Your video url string")!
do {
videoData = try Data(contentsOf: URL(string: "Your video url string")!)
print(videoData)
var strDesc : String
strDesc = ""
let videoObject: [String : Any] = ["title": "application Name", "description": strDesc, pathURL.absoluteString: videoData]
let uploadRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/videos", parameters: videoObject, httpMethod: "POST")
self.view!.isUserInteractionEnabled = false
uploadRequest.start(completionHandler: {(connection: FBSDKGraphRequestConnection, result: AnyObject, error: NSError) -> Void in
if error == error {
NSLog("Error")
}
else {
NSLog("Success")
}
} as! FBSDKGraphRequestHandler)
} catch {
print(error)
}
}
使用 SDK Facebook:
https://developers.facebook.com/docs/sharing/ios
视频 URL 视频 URL 必须是资产 URL。您可以获得视频资产 URL 例如来自 UIImagePickerController.
import FBSDKCoreKit
import FBSDKShareKit
import MobileCoreServices
import Photos
func createAssetURL(url: URL, completion: @escaping (String) -> Void) {
let photoLibrary = PHPhotoLibrary.shared()
var videoAssetPlaceholder:PHObjectPlaceholder!
photoLibrary.performChanges({
let request = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
videoAssetPlaceholder = request!.placeholderForCreatedAsset
},
completionHandler: { success, error in
if success {
let localID = NSString(string: videoAssetPlaceholder.localIdentifier)
let assetID = localID.replacingOccurrences(of: "/.*", with: "", options: NSString.CompareOptions.regularExpression, range: NSRange())
let ext = "mp4"
let assetURLStr =
"assets-library://asset/asset.\(ext)?id=\(assetID)&ext=\(ext)"
completion(assetURLStr)
}
})
}
func shareFacebbok() {
let content: FBSDKShareVideoContent = FBSDKShareVideoContent()
let videoURLs = Bundle.main.url(forResource: "video", withExtension: "mp4")!
createAssetURL(url: videoURLs) { url in
let video = FBSDKShareVideo()
video.videoURL = URL(string: url)
content.video = video
let shareDialog = FBSDKShareDialog()
shareDialog.shareContent = content
shareDialog.mode = .native
shareDialog.delegate = self
shareDialog.show()
}
}
我正在编写一个简单的测试应用程序,用于将视频从 iOS 上传到 Facebook。
我发现很难在网上找到 examples/tutorials 如何使用 Swift 执行此操作,因为 FacebookSDK 的所有文档都在 Objective-C.[=12= 中]
到目前为止,我有这个,它在我的 UI 上放置了一个共享按钮,但它看起来已禁用,据我所知,这是因为没有设置内容,但我看不出这是怎么可能的.
let video_content : FBSDKShareVideoContent = FBSDKShareVideoContent()
video_content.video = FBSDKShareVideo(videoURL: getVideoURL())
let button : FBSDKShareButton = FBSDKShareButton()
button.shareContent = video_content
button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 100) * 0.5, 50, 100, 25)
self.view.addSubview(button)
我的 getVideoURL()
函数 returns 一个肯定包含 url 到视频的 NSURL(我已经将它打印到控制台并检查它指向我存储在较早的文件夹)。
看了社交框架,可惜不能用,好像只能分享照片,不能分享视频。
我使用的是最新版本的 Xcode、Swift 和 Facebook SDK。
我在 objective c 中做过这个,我也遇到过类似的问题。不知道这是否适用于 swift.
问题是,如果出于某种原因,视频必须存储在 NSDocumentDirectory
或 NSTemporaryDirectory
中,这样她才能工作。不是你的情况。
虽然你可以在最坏的情况下使用 FBSDKGraphRequest
和 /me/Videos
我了解到您尝试使用的这种分享视频的方式,可以直接从照片库中获取链接。正如您在 this example
中看到的目前在objective-c
中只有示例,希望对您有所帮助
- (void)uploadVideoWithoutSettingsCredentials:(NSURL *)videoUrl withTitle:(NSString *)title withDesc:(NSString *)desc withPrivacy:(NSString *)privacy
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^{
NSError * error = nil;
NSData * videoData = [NSData dataWithContentsOfURL:videoUrl options:0 error:&error];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:4L];
[params setObject:videoData forKey:[NSString stringWithFormat:@"%@.MOV",title]];
[params setObject:desc forKey:@"description"];
NSString *privacyString = @"EVERYONE";
if (privacy.length > 0)
privacyString = privacy;
NSDictionary *privacyDict = [[NSDictionary alloc] initWithObjectsAndKeys: privacyString, @"value", nil];
[params setObject:[Utils objectToJsonString:privacyDict] forKey:@"privacy"];
dispatch_async(dispatch_get_main_queue(), ^{
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"/me/videos" parameters:params HTTPMethod:@"POST"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(@"RESPONSE!!! /me/videos");
NSLog(@"result %@",result);
NSLog(@"error %@",error);
dispatch_async(dispatch_get_main_queue(), ^{
if (!error) {
[[[UIAlertView alloc] initWithTitle:@"Success" message:@"Your clip was posted!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];
} else {
[[[UIAlertView alloc] initWithTitle:@"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil] show];
}
});
}];
});
});
}
您可以更改为 swift 语法,使用 Xcode 自动完成功能。
您可以使用语法 swift 和 this
来帮助自己我在我的应用程序中使用了这段代码,对我来说效果很好。
此代码适用于 Objective-C,但您可以在将其转换为 swift 语法后在 swift 中使用相同的代码。
希望对您有所帮助。
尝试下面的代码。
-(void) uploadVideoOnFacebook
{
NSURL *pathURL;
NSData *videoData;
pathURL = [NSURL URLWithString:self.strUploadVideoURL];
videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.strUploadVideoURL]];
NSString *strDesc;
strDesc = txtCaption.text;
NSDictionary *videoObject = @{@"title": @"application Name",@"description": strDesc,[pathURL absoluteString]: videoData};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:@"me/videos" parameters:videoObject HTTPMethod:@"POST"];
[self.view setUserInteractionEnabled:NO];
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
NSLog("Success");
else
NSLog("Error");
}];
}
@AngryDuck
试试这个代码它会起作用
func uploadVideoOnFacebook() {
var pathURL: NSURL
var videoData: NSData
pathURL = NSURL(string: self.strUploadVideoURL)!
videoData = NSData.dataWithContentsOfURL(NSURL(string: self.strUploadVideoURL)!)
NSString * strDesc
strDesc = txtCaption.text!
var videoObject: [NSObject : AnyObject] = ["title": "application Name", "description": strDesc, pathURL.absoluteString(): videoData]
var uploadRequest: FBRequest = FBRequest(graphPath: "me/videos", parameters: videoObject, HTTPMethod: "POST")
self.view!.userInteractionEnabled = false
uploadRequest.startWithCompletionHandler({(connection: FBRequestConnection, result: AnyObject, error: NSError) -> Void in
if !error {
NSLog("Success")
}
else {
NSLog("Error")
}
})
}
转换成swift3和4:- 试试这个
func uploadVideoOnFacebook() {
var pathURL: URL
var videoData: Data
pathURL = URL(string: "Your video url string")!
do {
videoData = try Data(contentsOf: URL(string: "Your video url string")!)
print(videoData)
var strDesc : String
strDesc = ""
let videoObject: [String : Any] = ["title": "application Name", "description": strDesc, pathURL.absoluteString: videoData]
let uploadRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/videos", parameters: videoObject, httpMethod: "POST")
self.view!.isUserInteractionEnabled = false
uploadRequest.start(completionHandler: {(connection: FBSDKGraphRequestConnection, result: AnyObject, error: NSError) -> Void in
if error == error {
NSLog("Error")
}
else {
NSLog("Success")
}
} as! FBSDKGraphRequestHandler)
} catch {
print(error)
}
}
使用 SDK Facebook:
https://developers.facebook.com/docs/sharing/ios
视频 URL 视频 URL 必须是资产 URL。您可以获得视频资产 URL 例如来自 UIImagePickerController.
import FBSDKCoreKit
import FBSDKShareKit
import MobileCoreServices
import Photos
func createAssetURL(url: URL, completion: @escaping (String) -> Void) {
let photoLibrary = PHPhotoLibrary.shared()
var videoAssetPlaceholder:PHObjectPlaceholder!
photoLibrary.performChanges({
let request = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
videoAssetPlaceholder = request!.placeholderForCreatedAsset
},
completionHandler: { success, error in
if success {
let localID = NSString(string: videoAssetPlaceholder.localIdentifier)
let assetID = localID.replacingOccurrences(of: "/.*", with: "", options: NSString.CompareOptions.regularExpression, range: NSRange())
let ext = "mp4"
let assetURLStr =
"assets-library://asset/asset.\(ext)?id=\(assetID)&ext=\(ext)"
completion(assetURLStr)
}
})
}
func shareFacebbok() {
let content: FBSDKShareVideoContent = FBSDKShareVideoContent()
let videoURLs = Bundle.main.url(forResource: "video", withExtension: "mp4")!
createAssetURL(url: videoURLs) { url in
let video = FBSDKShareVideo()
video.videoURL = URL(string: url)
content.video = video
let shareDialog = FBSDKShareDialog()
shareDialog.shareContent = content
shareDialog.mode = .native
shareDialog.delegate = self
shareDialog.show()
}
}