I'm developing an iOS app which user WebServices and I find Alamofire just perfect for what I'm doing but I'm having a problem; the app asks the user to login which is an Alamofire call and does it just fine.
The problem is, it has to create a collection view based on the content of another Alamofire request but is always printf("\n$%0.2f", amount[i]);
.
nil
The same codeblock works perfect for the Login but doesn't in this case BTW the debug Print always print func getJSON(URLToRequest: String) -> JSON {
let comp:String = (prefs.valueForKey("COMPANY") as? String)!
let params = ["company":comp]
var json:JSON!
let request = Alamofire.request(.POST, URLToRequest, parameters: params).responseJSON {
response in
switch response.result {
case .Success:
if let value = response.result.value {
json = JSON(value)
}
default:
json = JSON("");
}
}
debugPrint(request.response)
return json;
}
答案 0 :(得分:1)
您在设置之前尝试访问request.response
,请记住Alamofire 异步,因此您必须使用闭包返回JSON,但是请记住,Alamofire也会返回错误,因此我强烈建议您使用以下代码:
func getJSON(URLToRequest: String, completionHandler: (inner: () throws -> JSON?) -> ()) {
let comp:String = (prefs.valueForKey("COMPANY") as? String)!
let params = ["company":comp]
let request = Alamofire.request(.POST, URLToRequest, parameters: params).responseJSON {
response in
// JSON to return
var json : JSON?
switch response.result {
case .Success:
if let value = response.result.value {
json = JSON(value)
}
completionHandler(inner: { return json })
case .Failure(let error):
completionHandler(inner: { throw error })
}
}
诀窍是getJSON
函数采用类型为'inner'
的名为() throws -> JSON?
的附加闭包。这个闭包将提供计算结果,或者它将抛出。闭包本身是在计算过程中通过以下两种方法之一构建的:
inner: {throw error}
inner: {return json}
然后你就可以这样称呼它:
self.getJSON("urlTORequest") { (inner: () throws -> JSON?) -> Void in
do {
let result = try inner()
} catch let error {
print(error)
}
}
我希望这对你有所帮助。