首先:看起来有两种方法可以使用 GraphRequest 将视频上传到 facebook。使用“file_url”参数的一种。您提供一个 URL,facebook 从外部服务器下载视频文件。像这样很好用:
let params = [
"title": "...",
"description": "...",
"file_url": "http://example.com/videofile.mp4"
]
let rq = FBSDKGraphRequest(graphPath: "me/videos", parameters: params, HTTPMethod: "POST")
rq.startWithCompletionHandler { (conn, result, error) -> Void in
// handle error etc..
}
Facebook 从我的服务器加载文件,视频出现在我的时间线上。
另一种方法是使用“source”参数通过请求直接上传视频。这应该看起来像这样:
let videoURL = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("testvideo", ofType: "mp4")!)
let rawData = NSData(contentsOfURL: videoURL)!
let params = [
"title": "...",
"description": "...",
"source": rawData
]
但是,此错误消息失败:
The video you're trying to upload is in a format that isn't supported. Please try again with a video in a supported format.
查看文档,看起来视频数据必须在“multipart/form-data”中编码。该文档甚至提供了w3的链接。
然而,如何做到这一点对我来说仍然是一个谜。我尝试了很多组合使用其中的二进制视频数据制作表单数据字符串,例如:
var s = ""
s += "Content-Type: multipart/form-data; boundary=XXXXXXXXXXXXXXXXXXXX\r\n\r\n"
s += "--XXXXXXXXXXXXXXXXXXXX\r\n"
s += "Content-Type: application/octet-stream\r\n\r\n"
let p = "--XXXXXXXXXXXXXXXXXXXX--"
let data = NSMutableData()
data.appendData(s.asUTF8Data())
data.appendData(rawData)
data.appendData(p.asUTF8Data())
let params = [
"title": "...",
"description": "...",
"source": data
]
和其他组合
s += "Content-Transfer-Encoding: binary\r\n"
s += "Content-Disposition: file; filename=\"video.mp4\"\r\n"
但没有成功。我总是收到相同的错误消息:
The video you're trying to upload is in a format that isn't supported. Please try again with a video in a supported format.
那么如何将视频文件包装在表单数据中呢?
以防万一:不,很遗憾,我无法使用 FBSDK v4 中已经提供的视频共享功能。