0

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

David
  • 27
  • 4
  • 1
    Following [this](https://stackoverflow.com/questions/34060754/how-can-i-build-a-url-with-query-parameters-containing-multiple-values-for-the-s), you should be able to create `URL` and use that url here `var request = URLRequest(url: url!)`. – Kamran Aug 28 '19 at 18:11
  • Possible duplicate of [How can I build a URL with query parameters containing multiple values for the same key in Swift?](https://stackoverflow.com/questions/34060754/how-can-i-build-a-url-with-query-parameters-containing-multiple-values-for-the-s) – ZGski Aug 28 '19 at 20:11

1 Answers1

1

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()
vale
  • 1,376
  • 11
  • 25