Skip to content

Instantly share code, notes, and snippets.

@aijaz
Created August 22, 2017 16:11
Show Gist options
  • Save aijaz/34d16309bb3e866b4e2a78db246e13f4 to your computer and use it in GitHub Desktop.
Save aijaz/34d16309bb3e866b4e2a78db246e13f4 to your computer and use it in GitHub Desktop.
Simple example of using NSURLSession
import Foundation
import UIKit
class Network {
static let sharedInstance = Network()
private init() {
} //This prevents others from using the default '()' initializer for this class.
class func retrieveJsonAtLocation (urlString: String, completionHandler: @escaping ()->Void) {
let url = Bundle.main.url(forResource: urlString, withExtension: "json")
Network.retrieveJsonAtUrl(url: url!, completionHandler: completionHandler)
}
private class func retrieveJsonAtUrl(url: URL, completionHandler: @escaping ()->Void ) {
let conf = URLSessionConfiguration.default
let sessionWithoutDelegate = URLSession(configuration: conf)
let task:URLSessionDataTask = sessionWithoutDelegate.dataTask(with: url) { (data, response, error) in
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
Database.jsonData = jsonObject
completionHandler()
}
catch {
NSLog("Can't read json: \(error)")
}
sessionWithoutDelegate.finishTasksAndInvalidate()
}
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment