Swish2121
Swish2121

Reputation: 97

Swift 3 - Latest method for using API calls

What is the latest and most current way to manage API calls in an iOS app using swift 3?

Is it NSURLSession? or is there another way to do it that is newer?

Upvotes: -1

Views: 1168

Answers (3)

Ravi Dhorajiya
Ravi Dhorajiya

Reputation: 1531

In swift 3 - latest method call for api.

let url = URL(string: urlString)! //Pass the URL String format
var request = URLRequest(url: url)

_ = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else {
                    print(error?.localizedDescription ?? "No data")
                        self.ProgressViewHide()
                        return
                    }
     DispatchQueue.main.async {
          let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
                // Get Response on responseJSON
     }

}.resume()

Upvotes: 2

Jaydeep Vora
Jaydeep Vora

Reputation: 6223

So for new way in Swift 3.x you have to put like this.

Also, remember that your closure is work asynchronously, so I wrapped the call to be executed on main thread by using GCD.

let request = URLRequest(url: URL(string: "Put your url")!)

     let task = URLSession.shared.dataTask(with: request) {
                data, response, error in
                //print(error?.localizedDescription)

                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as AnyObject

                    //on main thread
                    DispatchQueue.main.async {
                        self.currentCode = json["code"]!! as! String

                    }

                }catch{
                    print("error\(error)")
                }
            }
            task.resume()

But, I suggest you to use more easy way to handle networking using Alamofire, https://github.com/Alamofire/Alamofire

Upvotes: 1

3stud1ant3
3stud1ant3

Reputation: 3606

In swift 3 NS prefix is removed, now following is the syntax for urlsession

URLSession.shared.dataTask(with: url!) { (data, response, error) in
         //do the work
}

Upvotes: 2

Related Questions