Skip to content

Instantly share code, notes, and snippets.

@ericleiyang

ericleiyang/GraphQLQuery.swift Secret

Last active Jul 9, 2020
Embed
What would you like to do?
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