0

I have this chunk of code written in obj-c that I am trying to translate in Swift 3 but I encountered NSURLConnection.sendSynchronousRequest which is both deprecated and for my knowledge bad since it is using a Synchronous operation.

Here is the code :

 NSData *responseData = [NSURLConnection sendSynchronousRequest:requestData returningResponse:&response error:&requestError];
 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];

Do you have any suggestion in how I may re-write this in a better way and why so?

anho
  • 1,705
  • 2
  • 20
  • 38
  • 2
    Possible duplicate of [NSURLConnection deprecated in iOS9](http://stackoverflow.com/questions/32441229/nsurlconnection-deprecated-in-ios9) – Larme Jan 24 '17 at 09:23

3 Answers3

1

This is the minimum code you would need to make an async request, if you are replacing a lot of calls you should make an API layer and reuse code rather than copy/pasta everywhere.

let url = URL(string: "http://myURL.com")!;
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        let dictionary = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments)
}
task.resume()
Sean Lintern
  • 3,103
  • 22
  • 28
0

URLSession is a replacement for NSURLConnection introduced in iOS 7. The URLSession class and related classes provide an API for downloading content via HTTP/HTTPS protocols. URLSession API is asynchronous by default.

Below is the simple Get request using URLSession API

 public func simpleNetworkRequest(completion: @escaping (_ JSON: [[String: Any]]?, _ error: Error?) -> Void) {

        // Set up the URL request
        let todoUrl: String = "https://jsonplaceholder.typicode.com/todos/1"

        guard let url = URL(string: todoUrl) else {
            print("Error: cannot create URL")
            return
        }

        let urlRequest = URLRequest(url: url)

        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        // make the request
        let task = session.dataTask(with: urlRequest) { (data, response, error) in

            guard error != nil else {
                print(error!.localizedDescription)
                completion(nil, error)
                return
            }

            // make sure we got data
            guard let responseData = data else {
                print("Error: did not receive data")
                completion(nil, nil)
                return
            }

            // parse the result as JSON, since that's what the API provides
            do {
                guard let JSON = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
                    print("error trying to convert data to JSON")
                    completion(nil, nil)
                    return
                }

                print("JSON response : \(JSON)")

                //code to parse json response and send it back via completion handler
                let result = JSON["result"] as? [[String: Any]]
                completion(result, nil)

            } catch let error {
                print(error.localizedDescription)
                completion(nil, error)
            }
        }

        task.resume()
    }

Below are free resources to get you stated

https://videos.raywenderlich.com/courses/networking-with-nsurlsession/lessons/1

https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started

Alternatively you can use Alamofore (recommended) to make network requests

Simple example to make request would be

    Alamofire.request("https://httpbin.org/get").responseJSON { response in
        print(response.request)  // original URL request
        print(response.response) // HTTP URL response
        print(response.data)     // server data
        print(response.result)   // result of response serialization

        if let JSON = response.result.value {
           print("JSON: \(JSON)")
        }
    }
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
-1

try like this

var request = NSMutableURLRequest(URL: NSURL(string: "request url")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var params = ["username":"username", "password":"password"] as Dictionary<String, String>

request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: [])

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    print("Response: \(response)")})

task.resume()
Satyanarayana
  • 1,059
  • 6
  • 16