Skip to content

Instantly share code, notes, and snippets.

@todbot
Last active December 12, 2016 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todbot/87bd012c93f06bf29f12d753975d8300 to your computer and use it in GitHub Desktop.
Save todbot/87bd012c93f06bf29f12d753975d8300 to your computer and use it in GitHub Desktop.
CrashSpace Sign JSON parsing in Swift, using struct, CrashSpace Sign JSON now returns an 'is_open' flag and a 'minutes_open' value
//: NEW CrashSpace Sign JSON parsing in Swift, using struct
// CrashSpace Sign JSON now returns an 'is_open' flag and a 'minutes_open' value
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]()
var isOpen = false
var minutesLeft = 0
let urlString = "https://crashspacela.com/sign2/json/";
let url = URL(string: urlString)
let task = URLSession.shared.dataTask(with:url!, completionHandler: {
(data, response, error) in
if error != nil {
print("oh no \(error)")
} else {
print("hi there; we got server response")
do {
// convert json string to object of dictionary of [string: any]
let buttonData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]
if let isOpen = buttonData["is_open"] as? Bool {
print("isOpen value: \(isOpen)")
}
if let minutesLeft = buttonData["minutes_left"] as? Double {
print("minutesLeft value: \(minutesLeft)")
}
// from https://developer.apple.com/swift/blog/?id=37
// convert json-ish array of 'Any' to struct, using extension
if let buttonPressesJson = buttonData["button_presses"] as? [Any] {
print("parsing buttonPress array...")
for item in buttonPressesJson {
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: id:\(b.id) msg:'\(b.msg)' for \(b.diff_mins) minutes at \(b.date)")
}
} catch let error as NSError {
print(error)
}
}
})
task.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