Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

rest - Upload Video to YouTube in Swift

EDIT: Still checking this frequently, will mark as solved when I or someone else helps me figure it out!

I am trying to upload a video to YouTube with YouTube’s REST API via Swift but I am having great difficulty figuring out what to do. I currently have a working GET request.

I'm confused on how the POST request URL should be constructed and where the file location is meant to go in the request. Also I think I should be using the resumbable upload protocol?

I have been struggling through various API's and documentation for 2 days now and am feeling hopeless.

Here is my working code for a GET request.

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()
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

HEADS UP (as of October 6, 2019) YouTube has decreased the API quota to 10,000 units per day. This is the equivalent of uploading 4 YouTube videos during a 24 hour time span. If your application use case relies on uploading many YouTube videos, I strongly advise you to reconsider. You can apply for an expansion of your daily quota, but Google is notoriously slow at getting back to you, if they do at all.


Yes, you need to create an app/project in YouTube and use the OAuth 2.0 Flow to post/insert videos to a channel to which you receive authorized access.

ONCE YOU HAVE YOUR ACCESS TOKEN FROM GOOGLE

use Alamofire as follows:

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)
            }
        })
}

Call the post function like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...