Alamofire等待回应

时间:2016-08-26 21:31:28

标签: swift networking alamofire

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

getAllPosts()

所以我遇到的问题是func getAllPosts(){ let token = getToken() Alamofire.request(.GET...) } func getToken(){ Alamofire.request(.POST...) } 函数被调用但未完成,getToken函数在设置令牌之前发出getAllPosts请求。

我不知道如何在继续GET请求之前等待getToken()函数中的令牌设置。

感谢这个问题的一些帮助。

2 个答案:

答案 0 :(得分:2)

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回答演示了相同的想法,但不是先调用getAllPosts(),而是首先调用getToken(),然后将结果传递给getAllPosts()。

答案 1 :(得分:1)

将其更改为此

func getAllPosts(){
    Alamofire.request(.GET...)
}

func getToken(){
    Alamofire.request(.POST...) {
        //SUCCESS BLOCK
        self.getAllPosts()
    }
}

现在不应该调用getAllPosts,而应该首先调用getToken,当POST请求完成时,它会转到Success Block,它会触发getAllPosts(),它现在有令牌。

解决此问题的另一种方法是使POST请求同步,而不是使用Aslam的Alamofire。同步请求在继续之前等待响应