Search code examples
swiftapiswift2nsdatansmutableurlrequest

How to get data from NSMutableURLRequest in Swift?


I'm trying to access to a dictionary API by the following code:

func apiConnection() {
        if let url = NSURL(string:"https://wordsapiv1.p.mashape.com/words/soliloquy") {
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "GET"
        request.addValue("aaabbbccc", forHTTPHeaderField: "X-Mashape-Key")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        print(request.HTTPBody)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            if error != nil {
                print("\(error)")
                return
            }

            print("\(response)")
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("\(responseString)")
        }
    }
}

Was I doing something wrong with the code? Sorry i'm pretty new in this area. The API I used is from https://market.mashape.com/wordsapi/wordsapi


Solution

  • You configured the task, but didn't start it

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        ...
    }
    task.resume() // Start the task