0
votes

I'm trying to connect to a database from an iOS application written in Swift. I can't find a function that replaces all the others, which have been marked as deprecated in the latest iOS update (9.2?). Some of those functions are sendSynchronousRequest and sendAsynchronousRequest.

I want to read the data and response from the database. I'm using the following code:

 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
        let res = response as! NSHTTPURLResponse
        if(res.statusCode >= 200 && res.statusCode < 300) {
            let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        }
    })

I'm getting an error at the first line:

Invalid conversion from throwing function of type '(NSURLResponse?, NSData?, NSError?) throws -> Void' to non-throwing function type '(NSURLResponse?, NSData?, NSError?) -> Void'

However, when I comment out the line in the if-statement (let jsonData:NSDictionary = try ...) the error disappears.

I know this function is deprecated; I can't find anything else.

How can I read the response from the AsynchronousRequest without errors?

1

1 Answers

1
votes

You are missing the do/catch block

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
    let res = response as! NSHTTPURLResponse
    do {
    if(res.statusCode >= 200 && res.statusCode < 300) {
        let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
    }
    } catch {

    }
}

But easier and better way in swift is this networking library: Alamofire

Example:

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serialization

             if let JSON = response.result.value {
                 print("JSON: \(JSON)")
             }
         }