到目前为止我的方法如下:
func siteInfo()->String?{ var info:NSDictionary! var str:String! Alamofire.request(.GET,MY_API_END_POINT).responseJSON {(request,response,JSON,error) in info = JSON as NSDictionary str = info["access_key"] as String //return str } return str }
这返回nil是一个问题.从我所看到的here,这是因为请求可能需要一段时间,所以关闭不会执行,直到返回.将返回值移动到闭包中的建议解决方案对我而言并不起作用,编译器只会大声喊叫(添加 – > String(请求,响应,错误)之后的“String”不是void的子类型“) .所提供的其他解决方案也是如此.
有任何想法吗?即使是与这个问题无关的源代码,即使用AlamoFire,这将是有帮助的.
谢谢!
func siteInfo(completionHandler: (String?,NSError?) -> ()) -> () { Alamofire.request(.GET,MY_API_END_POINT).responseJSON { (request,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 } }
在你提出的评论中:
So how would you save the info you collect from the get request if you
can only do stuff inside the closure and not effect objects outside of
the closure? Also,how to keep track to know when the request has
finished?
您可以从闭包中将获取请求的结果保存到类中的实例变量;没有关闭闭嘴阻止你这样做.你从那里做什么真的取决于,那么你想对这些数据做什么.
一个例子怎么样?
由于看起来您正在获得获取请求的访问密钥表单,也许您需要将其他功能中的未来请求.
在这种情况下,你可以这样做:
注意:异步编程是一个很大的话题;方式太多了,不能覆盖这里.这只是您如何处理从异步请求中获取的数据的一个示例.
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,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中的值.如果你做的其余的东西NeedingAccessKey的工作内部的封闭传递给getAccessKey,你可以确保你的accessKey将永远是有效的.如果你需要另一个需要accessKey的函数,那么就像写一个NeedingAccessKey一样的方式写.
public func somethingElse() { getAccessKey { (accessKey,error) in if accessKey != nil { // Do something else with accessKey } else { // Handle nil accessKey / error here } } }