NSURLConnection issues after Swift 2.0 update
Before Swift 2.0 update, this code worked fine for loading my JSON file from server using PHP Script:
let url = NSURL(string: webAdress)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0)
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
After updating, Xcode asked me to make some changes. I did and the code had no error, but it always throws ...
let url = NSURL(string: webAdress)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0)
var response: NSURLResponse? = nil
var reply = NSData()
do {
reply = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch {
print("ERROR")
}
Looking forward to your decisions!
source to share
Here's an example using the new NSURLSession - obviously NSURLConnection was deprecated in iOS 9.
let url = NSURL(string: webAddress)
let request = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
print(data)
print(response)
print(error)
})?.resume()
I think it's super clean, there just isn't a lot of documentation there. Let me know if you have any problem getting this to work.
source to share
Hi Maximilian, I have the same unresolved issue, the proposed Sidetalker solution using NSURLSession.dataTaskWithRequest is not what you are looking for as the NSURLSession API is very asynchronous (according to Apple documentation) and the code you implemented in swift 1.2 was synchronous. on the other hand, NSURLConnection was deprecated in iOS 9, so the code you wrote probably doesn't build, right?
My suggested solution:
let url = NSURL(string: webAdress)
let request: NSURLRequest = NSURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
var responseCode = -1
let group = dispatch_group_create()
dispatch_group_enter(group)
session.dataTaskWithRequest(request, completionHandler: {(_, response, _) in
if let httpResponse = response as? NSHTTPURLResponse {
responseCode = httpResponse.statusCode
}
dispatch_group_leave(group)
})!.resume()
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
//rest of your code...
please let me know if its ok now
source to share