swift – AlamoFire GET api请求不按预期工作

我正在尝试学习如何使用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
}

这返回nil是一个问题.从我所看到的here,这是因为请求可能需要一段时间,所以关闭不会执行,直到返回.将返回值移动到闭包中的建议解决方案对我而言并不起作用,编译器只会大声喊叫(添加 – > String(请求,响应,错误)之后的“String”不是void的子类型“) .所提供的其他解决方案也是如此.

有任何想法吗?即使是与这个问题无关的源代码,即使用AlamoFire,这将是有帮助的.

谢谢!

处理这个的一种方法是将一个闭包(我通常称之为一个完成Handler)传递给您的siteInfo函数,并在Alamofire.request的闭包中调用它:
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
        }
    }
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...