Skip to content

Instantly share code, notes, and snippets.

@parthjdabhi
Forked from seyhunak/Api.swift
Created January 2, 2017 08:35
Show Gist options
  • Save parthjdabhi/78e46207ee66af0fb385079d01137159 to your computer and use it in GitHub Desktop.
Save parthjdabhi/78e46207ee66af0fb385079d01137159 to your computer and use it in GitHub Desktop.
Swift - JSON API
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()
}
}
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