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()
}
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 { }
})
import GoogleSignIn
import GoogleAPIClientForREST
private let scopes = [kGTLRAuthScopeYouTube,
kGTLRAuthScopeYouTubeForceSsl,
kGTLRAuthScopeYouTubeUpload,
kGTLRAuthScopeYouTubeYoutubepartner]
private var service = GTLRYouTubeService()
private let youtubeObject = GTLRYouTube_Video()
func signInYoutube(){
GIDSignIn.sharedInstance()?.presentingViewController = self
GIDSignIn.sharedInstance()?.clientID = "Your_client_id"
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().scopes = scopes
if GIDSignIn.sharedInstance()?.hasPreviousSignIn() ?? false {
GIDSignIn.sharedInstance()?.restorePreviousSignIn()
} else {
GIDSignIn.sharedInstance()?.signIn()
}
}
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
self.service.authorizer = nil
} else {
self.service.authorizer = user.authentication.fetcherAuthorizer()
uploadVideoOnYoutube()
}
}
func uploadVideoOnYoutube() {
guard let videoUrl = Bundle.main.url(forResource: "sample_iTunes", withExtension: "mov")else {return}
//Status
let status = GTLRYouTube_VideoStatus()
status.privacyStatus = kGTLRYouTube_ChannelStatus_PrivacyStatus_Public
//Snippet
let snippet = GTLRYouTube_VideoSnippet()
snippet.title = "YOUR_VIDEO_TITLE"
//Upload parameters
let params = GTLRUploadParameters.init(fileURL: videoUrl, mimeType: "video/mov")
//YouTube Video object
youtubeObject.status = status
youtubeObject.snippet = snippet
let query = GTLRYouTubeQuery_VideosInsert.query(withObject: youtubeObject, part: "snippet,status", uploadParameters: params)
service.executeQuery(query, completionHandler: { (ticket, anyobject, error) in
if error == nil {
if let videoObject = anyobject as? GTLRYouTube_Video {
print(videoObject.identifier ?? "upload")
}
} else {
print(error?.localizedDescription)
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With