Saturday, May 28, 2016

Getting JSON from a Web API

let session = NSURLSession.sharedSession()
let url = NSURL(string: "http://swapi.co/api/people/1/")!

session.dataTaskWithURL(url) {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

    guard let theResponse = response as? NSHTTPURLResponse 
        where theResponse.statusCode == 200 else {
        print("Error in response.")
        return
    }
    
    if let responseData = data {
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(responseData, 
                                   options: NSJSONReadingOptions.AllowFragments)
            
            print(json)
        
        } catch {
            print("Could not serialize into json")
        }
    }
}.resume()

Very important, don't forget the .resume() at the end of the closure!

Now if you want to parse this JSON you can see this post on how to do it.
(Swift 2.2)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...