swift - Alamofire 等待响应

标签 swift networking alamofire

我的应用程序中有一个名为 getAllPosts() 的方法,这是一个获取数据的 GET 请求,但在该方法中我正在执行一个 POST请求获取access token,需要和getAllPosts()请求一起传递。所以基本上是这样的:

func getAllPosts(){
    let token = getToken()
    Alamofire.request(.GET...)
}

func getToken(){
    Alamofire.request(.POST...)
}

所以我遇到的问题是调用了 getToken 函数但未完成,并且 getAllPosts 函数发出了 GET 请求在设置 token 之前。

在继续 getAllPosts 请求之前,我不确定如何等待 token 在 getToken() 函数中设置。

在此问题上感谢您的帮助。

最佳答案

Alamofire 正在发出网络请求,因此在后台线程中异步运行。如果您查看 Alamofire 的 GitHub 中的示例页面,你会看到他们使用这样的语法:

Alamofire.request(.POST ...)
    .validate()
    .responseString { response in
        // This code will be executed after the token has been fetched.
    }

所以你会想做这样的事情:

func getAllPosts() {
    // This notation allows to pass a callback easily.
    getToken { appToken in

        // Unwrap the value of appToken into constant "token".
        guard let token = appToken else {
            // Handle the situation if the token is not there
            return
        }

        // The token is available to use here.
        Alamofire.request(.GET ...)
           ...
    }
}

/**
Gets the token.

- Parameters:
    - callback: Block of code to execute after the token has been fetched.
                The token might be nil in case some error has happened.
*/
func getToken(callback: (appToken: String?) -> Void) {
    Alamofire.request(.POST ...)
        .validate()
        .responseString { response in 
            // Check whether the result has succeeded first.
            switch response.result {
            case .Success:
                // Successful result, return it in a callback.
                callback(appToken: response.result.value)
            case .Failure:
                // In case it failed, return a nil as an error indicator.
                callback(appToken: nil)
            }
        }
}

我的回答包括更多的错误处理,但我的想法是您只需在 .responseString/.responseJSON/etc 中使用一个函数。打电话。

@Steelzeh's answer 演示了相同的想法,但他们不是先调用 getAllPosts(),而是先调用 getToken(),然后将结果传递给 getAllPosts()。

关于swift - Alamofire 等待响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39174891/

相关文章:

objective-c - 如何使用 Cocoa 或 Foundation 获取当前连接的网络接口(interface)名称?

Java 网络,不仅仅是简单的聊天室

iOS 以 Data Swift 形式上传图片

swift - 如何在 Swift 中对具有不同值的数组进行分组?

ios - 调度组通知不起作用

Java RMI 资源

ios - 为什么在 void 函数中会出现意外的非 void 返回值?

ios - UIVisualEffectView 和 UITableViewCell 内部的触摸

ios - 在快速静态错误中对自定义 UIView 进行动画处理

ios - 如何将 Alamofire 与 Json 字典中的数组一起使用?