Created
January 25, 2018 16:59
-
-
Save lukecurtis93/f7815e4ec5d18c72ab68035401d44e64 to your computer and use it in GitHub Desktop.
JSON, Swift, HTTP Headers and API’s
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
//: 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