在Swift中将视频上传到YouTube

编辑:经常检查这个,当我或其他人帮我解决时,将标记为已解决

我正在尝试通过Swift将YouTube视频上传到YouTube的REST API,但我很难搞清楚要做什么.我目前有一个工作的GET请求.

我对如何构造POST请求URL以及文件位置在请求中的位置感到困惑.另外我想我应该使用可重新上传的协议?

我已经在各种API和文档中苦苦挣扎了2天,感到绝望.

这是我的GET请求的工作代码.

func getRequestVideoInfo(){
    // Set up your URL
    let youtubeApi = "https://www.googleapis.com/youtube/v3/videos?part=contentDetails%2C+snippet%2C+statistics&id=AKiiekaEHhI&key=" + apiKey
    let url = NSURL(string: youtubeApi)

    // Create your request
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!,completionHandler: { (data,response,error) -> Void in
        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!,options: NSJSONReadingOptions.AllowFragments) as? [String : AnyObject] {

                print("Response from YouTube: \(jsonResult)")
            }
        }
        catch {
            print("json error: \(error)")
        }

    })

    // Start the request
    task.resume()
}
是的,您需要在YouTube中创建应用/项目,并使用OAuth 2.0 Flow将视频发布/插入您获得授权访问权限的频道.

一旦你从GOOGLE获得了访问权限

使用Alamofire如下:

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,error in
                    print(response)
                    callback(true)
                }
            case .Failure(_):
                callback(false)
            }
        })
}

像这样调用post函数

postVideoToYouTube(accesstoken,callback: { success in
if success { }
})

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...