Skip to content

Instantly share code, notes, and snippets.

@jquave
Created June 8, 2014 16:31
Show Gist options
  • Select an option

  • Save jquave/4485973b3c5b968eea7e to your computer and use it in GitHub Desktop.

Select an option

Save jquave/4485973b3c5b968eea7e to your computer and use it in GitHub Desktop.
In your APIController:
Modify the protocol to understand arrays:
protocol APIControllerProtocol {
func didRecieveAPIResults(results: NSDictionary)
func didRecieveAPIResults(results: NSArray)
}
Add a get function to perform arbitrary gets on URLs
func get(path: String) {
let url: NSURL = NSURL(string: path)
let request: NSURLRequest = NSURLRequest(URL: url)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error? {
println("ERROR: \(error.localizedDescription)")
}
else {
var error: NSError?
//let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error)
let dictResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
let arrResults = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSArray
// Now send the JSON result to our delegate object
if error? {
println("HTTP Error: \(error?.localizedDescription)")
}
else {
println("Results recieved")
if let results = dictResult {
self.delegate?.didRecieveAPIResults(results)
}
else {
if let results = arrResults {
self.delegate?.didRecieveAPIResults(results)
}
else {
var strResponse = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Could not deserialize json, is it valid? \(strResponse)")
}
}
}
}
})
}
Call it:
self.api.get("http://ec2-54-188-237-219.us-west-2.compute.amazonaws.com/signals/application/1")
Show the results in the callback:
func didRecieveAPIResults(results: NSArray) {
//println(results)
for itemInfo in results {
if let itemDict = itemInfo as? NSDictionary {
println(itemDict["title"])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment