Making HTTP calls ( GET, POST etc ) from Swift ( iOS)

266 views Asked by At

I am fairly new to swift programming language and I am trying to find a way to make a HTTP/API call from swift. I know how to do it exactly in Javascript because I have worked with it before quite a lot. But I can't seem to figure out in swift.

I found this code online and I have been testing this in XCODE Playground. But it is returning "nil"

The Code is below:

//: Playground - noun: a place where people can play

import UIKit
import XCPlayground // add this in

XCPSetExecutionShouldContinueIndefinitely(continueIndefinitely: true)

var str = "Hello, playground"

// create a session object
let session = NSURLSession(
configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

// make a network request for a URL, in this case our endpoint
    session.dataTaskWithURL(NSURL(string: "http://echo.jsontest.com/key/value/one/two")!,
    completionHandler: { (taskData, taskResponse, taskError) -> Void in

    // create an NSArray with the JSON response data
    var jsonReadError:NSError?

    let jsonArray = NSJSONSerialization.JSONObjectWithData(
        taskData, options: nil, error: &jsonReadError) as! [AnyObject]

 }).resume()

Can anyone tell me what am I doing wrong. Thank you. If I have made a mistake please let me know or if you need further information please let me know.

1

There are 1 answers

0
Reming Hsu On BEST ANSWER

Try this:

let jsonResult = NSJSONSerialization.JSONObjectWithData(taskData, options: NSJSONReadingOptions.MutableContainers, error: &jsonReadError) as! NSDictionary