I'm currently learning about web services in Swift. I have this URL that shows recent earthquakes and other information regarding it. The code at the bottom is what I have so far, once I run it, it NSLogs a string in JSON format from the URL. Here are 3 records I have from the string. How do I parse this JSON string and take out the ID, title, and populate that information into a dictionary?
html =
[
{
"response":1,
"message":"OK",
"count":50
},
{
"id":133813,
"title":"M 1.4 - 8km NE of Desert Hot Springs, California",
"link":"http://earthquake.usgs.gov/earthquakes/eventpage/ci37312936",
"source":"http://www.kuakes.com",
"north":34.02,
"west":116.443001,
"lat":34.019501,
"lng":-116.442497,
"depth":1,
"mag":1.4,
"time":"2015-02-04 23:41:06 UTC",
"timestamp":1423093266
},
{
"id":133814,
"title":"M 1.3 - 9km NE of Desert Hot Springs, California",
"link":"http://earthquake.usgs.gov/earthquakes/eventpage/ci37312920",
"source":"http://www.kuakes.com",
"north":34.021,
"west":116.441002,
"lat":34.020832,
"lng":-116.440666,
"depth":1,
"mag":1.3,
"time":"2015-02-04 23:40:26 UTC",
"timestamp":1423093226
},
{
"id":133815,
"title":"M 1.1 - 3km SW of Houston, Alaska",
"link":"http://earthquake.usgs.gov/earthquakes/eventpage/ak11502658",
"source":"http://www.kuakes.com",
"north":61.604,
"west":149.867004,
"lat":61.6035,
"lng":-149.866806,
"depth":48,
"mag":1.1,
"time":"2015-02-04 23:38:42 UTC",
"timestamp":1423093122
}
The code
override func viewDidLoad() {
super.viewDidLoad()
let httpMethod = "GET"
/* We have a 15-second timeout for our connection */
let timeout = 15
var urlAsString = "http://www.kuakes.com/json/"
let url = NSURL(string: urlAsString)
/* Set the timeout on our request here */
let urlRequest = NSMutableURLRequest(URL: url,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 15.0)
urlRequest.HTTPMethod = httpMethod
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse!,
data: NSData!,
error: NSError!) in
if data.length > 0 && error == nil{
let html = NSString(data: data, encoding: NSUTF8StringEncoding)
println("html = \(html)")
} else if data.length == 0 && error == nil{
println("Nothing was downloaded")
} else if error != nil{
println("Error happened = \(error)")
}
}
)
}
}