Skip to content

Instantly share code, notes, and snippets.

@ericleiyang
Last active July 9, 2020 06:28
Show Gist options
  • Save ericleiyang/96c631134a1ccd161f5d32ffb895e2a6 to your computer and use it in GitHub Desktop.
Save ericleiyang/96c631134a1ccd161f5d32ffb895e2a6 to your computer and use it in GitHub Desktop.
import Foundation
let swapiURL: URL = URL(string: "https://swapi.graph.cool/")!
func query() {
let query: String =
"""
query allFilms($filter: FilmFilter) {
allFilms(filter: $filter) {
title
director
starships {
pilots {
name
}
}
}
}
"""
struct Filter: Encodable {
let director: String
}
struct Variable: Encodable {
let filter: Filter
}
let filter = Filter(director: "Irvin Kershner")
let variable = Variable(filter: filter)
struct Payload<T: Encodable>: Encodable {
let variables: T
let query: String
}
let payload = Payload(variables: variable, query: allFilmsQuery)
var request = URLRequest(url: swapiURL)
request.httpBody = try! JSONEncoder().encode(payload)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else {
return print("data is null")
}
let swiftyJsonVar = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
print(swiftyJsonVar)
}.resume()
}
query()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment