Work with REST API in Swift 3 and Xcode 8 using URLSession and JSONSerialization

Category: Swift
Work with REST API in Swift 3 and Xcode 8 using URLSession and JSONSerialization

With the release of Swift 3 many changes have come to the language. Apple has updated their core frameworks as well. For example Foundation framework has gone through great changes. Before Swift 3 we used NSURLSession and NSJSONSerialization to reach a web service like REST API, download JSON and convert it to a readable format.

With the update of the Foundation framework NSURLSession and NSJSONSerialization became obsolete. Apple decided to get rid of NS prefix that used to stand for NeXTSTEP, a discontinued object-oriented, multitasking operating system based on UNIX that was developed by NeXT Computer in the late 1980s and early 1990s.

In this short article I’d like to share the way of working with REST APIs with Swift 3 and updated Foundation framework.

I usually do lots of explanations, but this time it’s not the case. I’m planning to do series of articles on App development with Swift 3 someday soon and I’ll cover many many details as well as working with REST API.

So, here’s the way to make a URLSession call and then perform JSONSerialization in Swift 3:

        let config = URLSessionConfiguration.default // Session Configuration
        let session = URLSession(configuration: config) // Load configuration into Session
        let url = URL(string: "YOUR URL STRING")!
        
        let task = session.dataTask(with: url, completionHandler: {
            (data, response, error) in
            
                if error != nil {
                    
                    print(error!.localizedDescription)
                    
                } else {
                    
                    do {
                        
                        if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
                        {
                            
                            //Implement your logic
                            print(json)
                            
                        }
                        
                    } catch {
                        
                        print("error in JSONSerialization")
                        
                    }
                    
                    
                }
            
        })
        task.resume()

Conclusion

Yeah, it’s a very short article, but hopefully it will be helpful for now. In case of any questions feel free to reach me either by email or Twitter. Enjoy and stay tuned for more stuff on Swift 3! Cheers!