Last active
June 26, 2017 17:18
-
-
Save shepting/cc7ecab2e9fff1f67186207ff2fdc0de to your computer and use it in GitHub Desktop.
Simple Swift Network Parsing
This file contains hidden or 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
// | |
// Networking.swift | |
// DemoPersonViewer | |
// | |
// Created by Steven Hepting on 6/23/17. | |
// Copyright © 2017 Hepting. All rights reserved. | |
// | |
import Foundation | |
struct User { | |
let first: String | |
let last: String | |
init?(json: [String: Any]) { | |
if let name = json["name"] as? [String: Any] { | |
if let first = name["first"] as? String { | |
self.first = first | |
} else { | |
print("Missing parameter 'first'. \(json).") | |
return nil } | |
if let last = name["last"] as? String { | |
self.last = last | |
} else { | |
print("Missing parameter 'last'. \(json).") | |
return nil | |
} | |
} else { | |
print("Missing parameter 'name'. \(json).") | |
return nil | |
} | |
} | |
} | |
func parseUsersJSON(from data: Data) -> [User] { | |
do { | |
if let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] { | |
var users = [User]() | |
if let results = json["results"] as? [[String: Any]] { | |
for userJSON in results { | |
if let user = User(json: userJSON) { | |
users.append(user) | |
} | |
} | |
} | |
return users | |
} | |
} catch { | |
print("Couldn't parse JSON: \(error)") | |
if let utf8String = String(data: data, encoding: String.Encoding.utf8) { | |
print("Received: \(utf8String)") | |
} | |
} | |
return [] | |
} | |
struct Client { | |
func loadUsers(completion: @escaping ([User], Error?) -> ()) { | |
let url = URL(string: "https://randomuser.me/api?results=20")! | |
let task = URLSession.shared.dataTask(with: url) {data, response, error in | |
var users = [User]() | |
if let data = data { | |
users = parseUsersJSON(from: data) | |
} | |
if let error = error { | |
print(error) | |
} | |
completion(users, error) | |
} | |
task.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment