Alamofire Get JSON Request and Response

I am trying to use the Yoda API and send a request using the Alamofire Fast structure. I know that the API works correctly since I tested the endpoint using the Mashape API key several times. I also see that requests are being sent (Mashape homepage on my request). 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 could be β€œThis is my first sentence” and it will automatically replace the spaces β€œ+” according to the API specification. Please ignore multiple println statements, they are for debugging only.

This is just a proof of conceptual code; it is intentionally not made by many errors, and not very for this reason. If you have any suggestions, I would appreciate it.

+6
source share
2 answers

For some reason, the problem is with the Alamofire request for JSON. This is how I handle 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 highly recommend you use SwiftyJSON to manage JSON better and easier, it is up to you.

Hope this helps you.

+4
source

An Alamofire request has several methods for responding to processing. Try processing the data and converting it to String. Confirm that the JSON response is normal.

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

Also validation error while parsing JSON data.

+4
source

Source: https://habr.com/ru/post/985136/


All Articles