Skip to content

Instantly share code, notes, and snippets.

@lukecurtis93
Created January 25, 2018 16:59
Show Gist options
  • Save lukecurtis93/f7815e4ec5d18c72ab68035401d44e64 to your computer and use it in GitHub Desktop.
Save lukecurtis93/f7815e4ec5d18c72ab68035401d44e64 to your computer and use it in GitHub Desktop.
JSON, Swift, HTTP Headers and API’s
//: Playground - noun: a place where people can play
import Foundation
import XCPlayground
import PlaygroundSupport
import UIKit
struct Industry: Codable {
let name: String
let id: Int
func getString() {
print( "Name: \(name), Id: \(id)" )
}
}
var industries = [Int: Industry]()
let urlString = "http://joben.test/industry"
let session = URLSession.shared
let url = URL(string: urlString)!
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
if let data = data
{
do{
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [Any] {
for anItem in object as! [Dictionary<String, AnyObject>] {
let industryName = anItem["name"] as! String
let industryID = anItem["id"] as! Int
let industry = Industry(name: industryName, id:industryID)
industries[industryID] = industry
industries[industryID]?.getString()
}
}
} catch {
print(error)
}
}
}).resume()
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment