我正在努力学习如何使用AlamoFire而我遇到了麻烦.
到目前为止,我的方法如下:
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
}
Run Code Online (Sandbox Code Playgroud)
这返回nil这是一个问题.从我在这里读到的,这是因为请求可能需要一段时间,因此在返回之前关闭不会执行.将返回值移动到闭包中的建议解决方案对我来说不起作用,编译器只是大喊(->String在之后添加(request,response,JSON,error)"'String'不是void的子类型").所提供的其他解决方案也是如此.
有任何想法吗?甚至一些与此问题无关的源代码(使用AlamoFire)也会有所帮助.
谢谢!
Mik*_*e S 31
处理这个的一种方法是将一个闭包(我通常称之为a 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)
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样调用它(不要忘记错误处理):
siteInfo { (str, error) in
if str != nil {
// Use str value
} else {
// Handle error / nil value
}
}
Run Code Online (Sandbox Code Playgroud)
那么如果你只能在闭包内部做东西而不影响闭包之外的对象,你将如何保存从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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用该设置,somethingNeedingAccessKey()第一次调用将触发获取访问密钥的请求.之后的任何调用somethingNeedingAccessKey()都将使用已存储的值self._accessKey.如果你somethingNeedingAccessKey在传递给闭包的其余部分工作getAccessKey,你可以确定你的accessKey总是有效的.如果您需要另一个需要的功能accessKey,只需按照相同的方式somethingNeedingAccessKey编写即可.
public func somethingElse() {
getAccessKey { (accessKey, error) in
if accessKey != nil {
// Do something else with accessKey
} else {
// Handle nil accessKey / error here
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14454 次 |
| 最近记录: |