Created
August 22, 2017 16:11
-
-
Save aijaz/34d16309bb3e866b4e2a78db246e13f4 to your computer and use it in GitHub Desktop.
Simple example of using NSURLSession
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
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