Showing posts with label nsurlrequest. Show all posts
Showing posts with label nsurlrequest. Show all posts

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)

Monday, May 9, 2016

Open Web Page in iOS

Showing a web page in your iOS app is a two step process. Maybe even a one step process if you already have a web view setup.
// 1. Setup the web view
let webView: WKWebView = WKWebView()
view.addSubview(webView)
webView.frame = view.frame

// 2. Setup the request
let url = NSURL(string: "http://swiftquickstart.blogspot.com/")!
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
Recommendations:
  • The webView variable should be global in your view controller
  • Set the webView.frame in viewDidLayoutSubviews so when you change orientation it gets reset

(Swift 2.2)

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...