NSURLConnection throws after updating to Swift 2.0

6.7k views Asked by At

Before the Swift 2.0 Update this code worked perfectly to download my JSON File from the Server with a 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 the Update Xcode asked me to do 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 solutions!

2

There are 2 answers

8
Sidetalker On

Here's an example using the new NSURLSession - apparently NSURLConnection has been 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's just not much documentation on it. Let me know if you have any trouble getting this to work.

0
Gutty1 On

Maximilian hi, I have the same unsolved issue, the proposed solution by Sidetalker using NSURLSession.dataTaskWithRequest is not what you looking for since the NSURLSession API is highly asynchronous (according with Apple documentation) and the code you had implemented in swift 1.2 was synchronous. in the other hand, NSURLConnection has been deprecated in iOS 9 therefore the code you wrote is probably not building, right?

my suggested solution is:

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 now OK