Last active
December 9, 2016 08:26
-
-
Save todbot/6f4bf8c22970c8c0dae10dc34c7bb635 to your computer and use it in GitHub Desktop.
CrashSpace Sign JSON parsing in Swift, using struct
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
//: CrashSpace Sign JSON parsing in Swift, using struct | |
import Cocoa | |
import Foundation | |
struct ButtonPress { | |
let id: String | |
let msg: String | |
let diff_mins: Int | |
let date: String | |
let date_epoch: String | |
let type: String | |
} | |
extension ButtonPress { | |
// 'json' is dictionary where key is string, value is any | |
init?(json: [String: Any]) { | |
guard let id = json["id"] as? String, | |
let msg = json["msg"] as? String, | |
let diff_mins = json["diff_mins_max"] as? Int, | |
let date = json["date"] as? String, | |
let date_epoch = json["date_epoch"] as? String, | |
let type = json["type"] as? String | |
else { | |
return nil | |
} | |
self.id = id | |
self.msg = msg | |
self.diff_mins = diff_mins | |
self.date = date | |
self.date_epoch = date_epoch | |
self.type = type | |
} | |
} | |
// array to hold our future list of ButtonPress objects | |
var buttonPresses = [ButtonPress]() | |
let urlString = "https://crashspacela.com/sign2/json/"; | |
let url = URL(string: urlString) | |
URLSession.shared.dataTask(with:url!) { (data, response, error) in | |
if error != nil { | |
print("oh no \(error)") | |
} else { | |
print("hi there; we got server response") | |
do { | |
let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [Any] | |
print("all items:"); | |
print("-------------"); | |
for item in parsedData { | |
let item = item as! [String:Any] // recast as array w/ key:string, val:any | |
let id = item["id"] as! String | |
let msg = item["msg"] as! String | |
let diff_mins = item["diff_mins_max"] as! Int | |
print(" item: id:\(id), msg:\(msg), diff_mins:\(diff_mins)") | |
} | |
// from https://developer.apple.com/swift/blog/?id=37 | |
// convert json-ish data to struct, using extension | |
for item in parsedData { | |
let item = item as! [String:Any] | |
if let buttonPress = ButtonPress(json: item) { | |
buttonPresses.append(buttonPress) | |
} | |
} | |
print("\nbuttonPress structs"); | |
print("-------------"); | |
for b in buttonPresses { | |
print("buttonPress: \(b.id) '\(b.msg)' for \(b.diff_mins) minutes at \(b.date)") | |
} | |
} catch let error as NSError { | |
print(error) | |
} | |
} | |
}.resume() | |
// in playground, loop forever so the task above completes | |
var waiting = true | |
while( waiting ) { | |
sleep(10) | |
print("sleeping...") | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment