Skip to content

Instantly share code, notes, and snippets.

@pakirby1
Last active May 16, 2019 08:31
Show Gist options
  • Save pakirby1/c02f91c9d685230a7c00abe4469f12fb to your computer and use it in GitHub Desktop.
Save pakirby1/c02f91c9d685230a7c00abe4469f12fb to your computer and use it in GitHub Desktop.
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
view.addSubview(label)
self.view = view
let damageDeck = "https://raw.githubusercontent.com/guidokessels/xwing-data2/master/data/damage-decks/core.json"
loadJSON(from: damageDeck)
}
func loadJSON(from: String) {
// validate the incoming url
guard let url = URL(string: from) else {
print("Invalid url: \(from)")
return
}
let request = URLRequest(url: url)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) {
(data, response, error) in
// do we have an error?
guard error == nil else {
print("Error encountered requesting \(from), \(String(describing: error))")
return
}
// do we have data?
guard let response = data else {
print("Error: did not receive data")
return
}
// parse data, this code is dependent on the structure of the JSON
/*
Since we have a dictionary that has a key of type String and a value
of type [Any], we'll need to first parse the JSON into a dictionary
{
"cards": [
{
"title": "Panicked Pilot",
"amount": 2,
"type": "Pilot",
"text": "Gain 2 stress tokens. Then repair this card."
},
{
"title": "Blinded Pilot",
"amount": 2,
"type": "Pilot",
"text": "While you perform an attack, you can modify your
dice only by spending [Force] for their default effect.
Action: Repair this card."
}
}
*/
print(response.description)
do {
// json root
guard let rootDictionary = try JSONSerialization.jsonObject(
with: response,
options: []) as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
// cards dictionary
if let cards = rootDictionary["cards"] as? [[String: Any]] {
for card in cards {
if let title = card["title"] as? String {
print(title)
}
}
}
} catch {
print("failed to serialize data to JSON")
return
}
}
task.resume()
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment