我正在尝试使用Yoda API并使用Alamofire Swift框架发送请求。我知道API正常运行,因为我已经多次使用Mashape API密钥测试了端点。我还可以看到正在发送请求(我的应用程序下Mashape的主页)。但是我的JSON响应始终是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);
}
}
该字字符串可以是“这是我的第一句话”,它会自动替换为空格“+”为按照API SPEC。请忽略多个println
语句,它们仅用于调试。
这只是概念代码的证明,其目的是不做太多错误检查,因此也不是很漂亮。如果您有任何建议,我将不胜感激。
出于某种原因,Alamofire请求JSON也是一个问题。这是我使用Alamofire处理JSON请求的方式:
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)
}
})
我强烈建议您使用SwiftyJSON以更好,更轻松的方式管理JSON,这取决于您。
希望对您有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句