处理此问题的一种方法是将闭包(我通常称之为completionHandler)传递给您的siteInfo 函数并在Alamofire.request 的闭包中调用它:
func siteInfo(completionHandler: (String?, NSError?) -> ()) -> () {
Alamofire.request(.GET, MY_API_END_POINT).responseJSON {
(request, response, JSON, error) in
let info = JSON as? NSDictionary // info will be nil if it's not an NSDictionary
let str = info?["access_key"] as? String // str will be nil if info is nil or the value for "access_key" is not a String
completionHandler(str, error)
}
}
然后这样调用它(不要忘记错误处理):
siteInfo { (str, error) in
if str != nil {
// Use str value
} else {
// Handle error / nil value
}
}
在您询问的 cmets 中:
那么,如果您保存从 get 请求中收集的信息,您将如何
只能在闭包内做事,不能影响外面的对象
关闭?此外,如何跟踪以了解请求何时
完成了吗?
您可以从闭包内部将 get 请求的结果保存到类中的实例变量中;关闭并没有阻止您这样做。你从那里做什么真的取决于你想用这些数据做什么。
举个例子怎么样?
由于您似乎获得了一个获取请求的访问密钥表单,因此您可能需要它来处理其他函数中的未来请求。
在这种情况下,您可以这样做:
注意:异步编程是一个巨大的话题;这里太多了。这只是您如何处理从异步请求返回的数据的一个示例。
public class Site {
private var _accessKey: String?
private func getAccessKey(completionHandler: (String?, NSError?) -> ()) -> () {
// If we already have an access key, call the completion handler with it immediately
if let accessKey = self._accessKey {
completionHandler(accessKey, nil)
} else { // Otherwise request one
Alamofire.request(.GET, MY_API_END_POINT).responseJSON {
(request, response, JSON, error) in
let info = JSON as? NSDictionary // info will be nil if it's not an NSDictionary
let accessKey = info?["access_key"] as? String // accessKey will be nil if info is nil or the value for "access_key" is not a String
self._accessKey = accessKey
completionHandler(accessKey, error)
}
}
}
public func somethingNeedingAccessKey() {
getAccessKey { (accessKey, error) in
if accessKey != nil {
// Use accessKey however you'd like here
println(accessKey)
} else {
// Handle error / nil accessKey here
}
}
}
}
使用该设置,第一次调用somethingNeedingAccessKey() 将触发获取访问密钥的请求。之后对somethingNeedingAccessKey() 的任何调用都将使用已存储在self._accessKey 中的值。如果您在传递给getAccessKey 的闭包内完成somethingNeedingAccessKey 的其余工作,您可以确定您的accessKey 将始终有效。如果您需要另一个需要accessKey 的函数,只需按照somethingNeedingAccessKey 的编写方式编写即可。
public func somethingElse() {
getAccessKey { (accessKey, error) in
if accessKey != nil {
// Do something else with accessKey
} else {
// Handle nil accessKey / error here
}
}
}