Created
June 8, 2014 16:31
-
-
Save jquave/4485973b3c5b968eea7e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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