var request: NSURLRequest = NSURLRequest(NSURL(string: <your url path>))
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)
var data: NSMutableata = NSMutableData()
Now you must implement a few methods that will be called when a response is received, when data is being appended, and when the connection is done loading data.
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
// clear the array for new data to be loaded
data = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
// appending data to array
data.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
// anything that you want done after data loads
}
The first method is called when the connection receives a response. In our case this will be right when the connection is created because we set the startImmediatly parameter to true. If this was set to false, then you would need to start the connection explicitly by making an asynchronous or synchronous call to the connection by placing this line (or one similar) where you want the connection to start. I did not add any parameters to the call because there are so many variations on the method; you will need to choose which one best suits your needs.
NSURLConnection.sendAsynchronousRequest()
let json = JSON(data : data[0])
Alternatively you could loop through your array of data if you had more than one instance of data. Now comes the easy part: actually accessing the elements. Given an example JSON from json.org:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
}
},
"required": ["id"]
}
Say you wanted to access the title:
let title = json["title"].stringValue
or the description of the id:
let description = json["properties"]["id"]["description"]
or the required array (it only contains one thing but the [] signify an array):
let requiredArray = json["required"].arrayValue
or if we just wanted the first element:
let requiredArrayFirstValue = json["required"][0]
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)