Reputation: 27
first, I have to say, that there are many links here that user asked same question, but none of them helps, so please don't remove my question.
I want to videos from youtube API, there are some parameters that I should send with, first I add them into header but apparently it doesn't help.
Here is my url
let url = Url(String: "https://www.googleapis.com/youtube/v3/playlistItems")
and here are the parameters (I added to header but it's wrong)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.allHTTPHeaderFields = [
"part" : "snippet",
"key" : api_key,
"playlistId": trailerPlayListId
]
In some post, I read that I can change URL
to URLComponents
and add queryItems
, but when I do that, I can't add it to URLRequest
, it need URL
var request = URLRequest(url: url!)
Could anyone help me on that? Thanks
Upvotes: 0
Views: 936
Reputation: 1426
I'm not sure if they're get parameters or http header field so I've added the values to both. Remove the ones you don't need.
import UIKit
import Foundation
var api_key = ""
var trailerPlayListId = ""
var url = URLComponents(string: "https://www.googleapis.com/youtube/v3/playlistItems")!
url.queryItems = [URLQueryItem(name: "part", value: "snippet"),
URLQueryItem(name: "key", value: api_key),
URLQueryItem(name: "playlistId", value: trailerPlayListId)]
let request = NSMutableURLRequest(url: url.url!)
request.httpMethod = "GET"
//not sure if these are headers or not, they look more like GET fields
request.allHTTPHeaderFields = [
"part" : "snippet",
"key" : api_key,
"playlistId": trailerPlayListId
]
let dataTask = URLSession.shared.dataTask(with: request as URLRequest) {data,response,error in
do {//TODO: Parse Response
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {
print("data \(jsonResult)")
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
dataTask.resume()
Upvotes: 1