10

I'm trying to use the Yoda API and send a request using the Alamofire Swift framework. I know that the API is correctly working, as I have tested the endpoint with my Mashape API key multiple times. I can also see that the requests are being sent (homepage of Mashape under my application). However my JSON response is always nil.

func handleRequest(words:String){
        var saying = words.stringByReplacingOccurrencesOfString(" ", withString: "+");
        saying = "?sentence=" + saying;
        let url = NSURL(string: (baseURL+saying));
        println(url);
        var response:String;
        Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = additionalHeaders;
        Alamofire.request(.GET, url!).responseJSON { (_, _, JSON, _) in
            println(JSON);

        }
    }

The words string can be "This is my first sentence" and it will automatically replace the spaces with "+" as per the API spec. Please Ignore the multiple println statements, they are just for debugging.

This is just proof of concept code, its purposely not doing much error checking and isn't pretty for that reason. If you have any suggestions I would appreciate them.

Patrick Zawadzki
  • 456
  • 2
  • 6
  • 26
  • It'll be much easier to help you out if you can include the actual URL being used. – David Berry Apr 14 '15 at 19:30
  • Sure, an example that would work as passed into the `url` constant https://yoda.p.mashape.com/yoda?sentence=You+will+learn+how+to+speak+like+me+someday.++Oh+wait. – Patrick Zawadzki Apr 14 '15 at 20:24
  • That last closure argument that you're currently ignoring with `_` is an `NSError` that you can check to see why `JSON` might be `nil`. – mattt Apr 15 '15 at 15:19

2 Answers2

6

Alamofire request have several method for handle response. Try to handle data response and convert it to String. Confirm that response JSON is normal.

Alamofire.request(.GET, url!).response { (_, _, data, error) in
    let str = NSString(data: data, encoding: NSUTF8StringEncoding)
    println(str)
    println(error)
}

Also checkout error while parsing JSON data.

Gralex
  • 4,285
  • 7
  • 26
  • 47
6

For some reason it's an issue I've too with the Alamofire request for JSON. It is the way I handle the JSON requests using Alamofire :

Alamofire.request(.GET, urlTo, parameters: nil, encoding: .URL).responseString(completionHandler: {
        (request: NSURLRequest, response: NSHTTPURLResponse?, responseBody: String?, error: NSError?) -> Void in

        // Convert the response to NSData to handle with SwiftyJSON
        if let data = (responseBody as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
            let json = JSON(data: data)
            println(json)
        }
})

I strongly recommend you using SwiftyJSON to manage the JSON in a better and easy way, it's up to you.

I hope this help you.

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105