使用 Swift 通过 REST API 为 youtube 上传设置片段数据 [英] Setting snippet data for youtube upload via REST API using Swift
问题描述
我能够使用以下代码通过他们的 REST API 成功将视频上传到 youtube:
I'm able to successfully upload a video to youtube via their REST API using the following code:
func postVideoToYouTube(token: String, callback: Bool -> Void){
let headers = ["Authorization": "Bearer (token)"]
let path = NSBundle.mainBundle().pathForResource("video", ofType: "mp4")
let videodata: NSData = NSData.dataWithContentsOfMappedFile(path!)! as! NSData
upload(
.POST,
"https://www.googleapis.com/upload/youtube/v3/videos?part=id",
headers: headers,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: videodata, name: "video", fileName: "video.mp4", mimeType: "application/octet-stream")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { request, response, error in
print(response)
callback(true)
}
case .Failure(_):
callback(false)
}
})
}
我现在想编辑上面的代码,以便我可以在初始上传时设置一些snippet
数据,特别是title
和description
.
I now would like to edit the above code so that I can set some snippet
data on the initial upload, specifically a title
and description
.
我尝试使用另一种 Alamofire
方法,它与上面的方法非常相似,只是它还需要一个 NSMutableURLRequest
作为参数.我制作了我的片段字典并将其设置为可变请求的 HTTPBody
属性.视频上传仍然有效,但我的代码段的标题和描述值仍未设置.
I tried using an alternative Alamofire
method that's very similar to the one above, only it also takes an NSMutableURLRequest
as a parameter. I crafted my snippet dictionary and set it as the HTTPBody
property of the mutable request. The video upload still works, but my snippet's title and description values are still not being set.
如何在将视频上传到 youtube 时设置一些片段信息?
How can I set some snippet info when uploading the video to youtube?
推荐答案
在multipartFormData块中为参数值添加一行如下(将代码放在视频项之前):
Add a line to the multipartFormData block for the parameter values as follows (place the code before the video item):
multipartFormData.appendBodyPart(data:"{'snippet':{'title' : 'TITLE_TEXT', 'description': 'DESCRIPTION_TEXT'}}".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"snippet", mimeType: "application/json")
post url 也应该改为 part=snippet
the post url should also be changed to part=snippet
https://www.googleapis.com/upload/youtube/v3/videos?part=snippet
即
.POST,
"https://www.googleapis.com/upload/youtube/v3/videos?part=snippet",
headers: headers,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data:"{'snippet':{'title' : 'TITLE_TEXT', 'description': 'DESCRIPTION_TEXT'}}".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"snippet", mimeType: "application/json")
multipartFormData.appendBodyPart(data: videodata, name: "video", fileName: "video.mp4", mimeType: "application/octet-stream")
},
这篇关于使用 Swift 通过 REST API 为 youtube 上传设置片段数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!