小编典典

使用Swift通过REST API设置YouTube上传的代码段数据

swift

我可以使用以下代码通过其REST API将视频成功上传到youtube:

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在初始上传时设置一些数据,特别是titledescription

我尝试使用一种Alamofire与上面的方法非常相似的替代方法,只是它也将a
NSMutableURLRequest作为参数。我编写了代码片段字典并将其设置为HTTPBody可变请求的属性。视频上传仍然有效,但是我的摘录的标题和描述值仍未设置。

将视频上传到youtube时如何设置一些片段信息?


阅读 388

收藏
2020-07-07

共1个答案

小编典典

在multipartFormData块中为参数值添加一行,如下所示(将代码放置在视频项之前):

multipartFormData.appendBodyPart(data:"{'snippet':{'title' : 'TITLE_TEXT', 'description': 'DESCRIPTION_TEXT'}}".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"snippet", mimeType: "application/json")

帖子网址也应更改为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")
},
2020-07-07