Skip to content

iOS Network Requests

Kevin Leong edited this page Mar 6, 2017 · 3 revisions

Network Requests in iOS

AlamoFire request

// ItemObject is a custom class
var items: [ItemObject]()

Alamofire.request("http://api.example.com/some-path).responseJSON() {
    // NSHTTPURLResponse object
    response in

    // response.result.value is a [String: Any] object
    // assuming the response contains a JSON array in the "items" field
    if let itemsResponse = (response.result.value as? [String: Any])?["items"] as? [[String: Any]] {
        for item in itemsResponse {
            let itemObject = ItemObject(responseMap: item)
            self.items.append(repo)
        }
    }
}

References

NSURLSession request

Making the network call

class func getMovies(path: String, onComplete: (NSData?, NSURLResponse?, NSError?) -> Void) {
        let url = createUrl("\(moviesPath)\(path)")!
        print("\(url)")

        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
        let task = session.dataTaskWithRequest(NSURLRequest(URL: url), completionHandler: onComplete)
        task.resume()
    }

    private class func createUrl(path: String) -> NSURL? {
        let urlComponent = NSURLComponents()

        urlComponent.scheme = scheme
        urlComponent.host = host
        urlComponent.path = path
        urlComponent.queryItems = [apiKeyQueryParam()]

        return urlComponent.URL
    }

    private class func apiKeyQueryParam() -> NSURLQueryItem {
        return NSURLQueryItem(name: apiKeyParam, value: apiKey)
    }

After network call completes

func onNowPlayingComplete(data: NSData?, response: NSURLResponse?, error: NSError?) {
        // Print out response information
        if let httpResponse = response as? NSHTTPURLResponse {
            print("status code: \(httpResponse.statusCode)")
            print("url: \(httpResponse.URL!)")
            print("headers:")
            for (key, value) in httpResponse.allHeaderFields {
                print("\t\(key): \(value)")
            }
        }

        if error != nil {
            // Handle HTTP request error
        }
        else {
            if let rawData = data {
                do {
                    // jsonResponse is either an NSArray or NSDictionary with String keys
                    let jsonResponse = try NSJSONSerialization.JSONObjectWithData(rawData, options: [])

                    // Conditionally
                    if let moviesJson = jsonResponse["results"] as? [[String: AnyObject]] {
                        for movieJson in moviesJson {
                            self.movies.append(Movie(parsedJson: movieJson))
                        }
                    }
                    else {
                        // Handle casting error
                    }

                }
                catch let error as NSError {
                    // Handle JSON parsing error
                    print("\(error.localizedDescription)")
                }
            }
            else {
                // Handle nil data object
            }
        }

        // Refresh table view on the main UI thread
        dispatch_async(dispatch_get_main_queue()) {
            self.moviesTableView.reloadData()
        }
    }

Making an exception for App Transport Security (ATS)

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>127.0.0.1</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict

References

Clone this wiki locally