使用 Alamofire 快速关闭 [英] Swift closure with Alamofire
问题描述
我正在对服务器进行 API 调用.我正在利用 Alamofire 来处理这个问题.我正在尝试创建一个函数,该函数使用 Alamofire 的 GET 函数返回一个基于自定义类的对象,该类包含此 GET 函数提供的各种输出.
I am making API calls to a server. I am leveraging Alamofire to handle this. I'm trying to create a function that uses Alamofire's GET function to return an object based on a custom class that holds the various outputs provided by this GET function.
我不清楚这样做的方式.
It's not clear to me the way in which to do this.
这是我的自定义类,用于保存有关响应的详细信息:
Here's my custom class that will hold details about the response:
import Foundation
class ResponsePackage {
var success = false
var response: AnyObject? = nil
var error: NSError? = nil
}
在另一个类中,我有以下功能:
In another class I have the following function:
func get(apiEndPoint: NSString) -> ResponsePackage {
let responsePackage = ResponsePackage()
Alamofire
.request(.GET, apiEndPoint)
.responseJSON {(request, response, JSON, error) in
responsePackage.response = JSON
responsePackage.success = true
responsePackage.error = error
}
return responsePackage
}
这将返回 nil
,因为在 return
执行之前对服务器的调用尚未完成.我知道我应该能够用闭包来做到这一点,但我不知道如何构造它.
This returns nil
as the call to the server is not complete before the return
gets executed. I know that I should be able to do this with closures, but I am not sure how to construct this.
推荐答案
{}
之间的代码相当于 Objective-C 中的代码块:这是一段异步执行的代码.
The code between the {}
is the equivalent of block in objective-C : this is a chunk of code that gets executed asynchronously.
您犯的错误是您放置 return 语句的位置:当您启动请求时,{}
中的代码在框架收到响应之前不会执行,因此当 return
语句到达,很可能,仍然没有响应.您可以简单地移动该行:
The error you made is where you put your return statement : when you launch your request, the code in {}
is not executed until the framework received a response, so when the return
statement is reached, chances are, there is still no response. You could simply move the line :
return responsePackage
在闭包内,所以 func
只有在收到响应时才返回.这是一种简单的方法,但它并不是真正的最佳方法:您的代码将卡在等待答案中.最好的方法是使用闭包.这看起来像:
inside the closure, so the func
return only when it has received a response. This is a simple way, but it's not really optimal : your code will get stuck at waiting for the answers. The best way you can do this is by using closure, too. This would look something like :
func get(apiEndPoint: NSString, completion: (response: ResponsePackage) -> ()) -> Bool {
let responsePackage = ResponsePackage()
Alamofire
.request(.GET, apiEndPoint)
.responseJSON {(request, response, JSON, error) in
responsePackage.response = JSON
responsePackage.success = true
responsePackage.error = error
completion(response: responsePackage)
}
}
这篇关于使用 Alamofire 快速关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!