-
-
Save parthjdabhi/78e46207ee66af0fb385079d01137159 to your computer and use it in GitHub Desktop.
Swift - JSON API
This file contains 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
class API { | |
let uri = "https://api.com/endpoint" // replace your api endpoint (json) | |
func getData(completionHandler: ((NSArray!, NSError!) -> Void)!) -> Void { | |
let url: NSURL = NSURL(string: uri)! | |
let ses = NSURLSession.sharedSession() | |
let task = ses.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in | |
if (error != nil) { | |
return completionHandler(nil, error) | |
} | |
var error: NSError? | |
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary | |
if (error != nil) { | |
return completionHandler(nil, error) | |
} else { | |
return completionHandler(json["results"] as [NSDictionary], nil) | |
} | |
}) | |
task.resume() | |
} | |
} |
This file contains 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
var items: NSMutableArray = [] | |
var api = API() | |
api.getData({data, error -> Void in | |
if (data != nil) { | |
dispatch_sync(dispatch_get_main_queue(), { | |
self.items = NSMutableArray(array: data) | |
self.tableView.reloadData() | |
completionHandler(NCUpdateResult.NewData) | |
}) | |
} else { | |
completionHandler(NCUpdateResult.Failed) | |
println(error) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment