-
-
Save ericleiyang/96c631134a1ccd161f5d32ffb895e2a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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