gpt4 book ai didi

ios - 延迟任务直到完成

转载 作者:行者123 更新时间:2023-11-28 10:40:07 26 4
gpt4 key购买 nike

“我如何延迟一个函数或一段代码?”是人们常问的一个问题。但这不是我在这里需要的。

我需要我的代码等待某个任务完成,否则我的函数会收到一个错误,指出我没有 access_token(因为代码不会等待从 Spotify 服务器获取数据)。

到目前为止,这是我的代码,尝试添加一个 DispatchGroup :

func getAccessToken() throws -> Spotify.JSONStandard {
var accessToken: Spotify.JSONStandard!

let group = DispatchGroup() // <- Create group
group.enter() // <- Enter group

Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: spotify.parameters, headers: nil).responseJSON(completionHandler: {
response in
// Check if response is valid
if let newValue = response.result.value as? Spotify.JSONStandard {
accessToken = newValue
}

group.leave() // <- Leave group
})

group.wait() // <- Wait until task is completed

// \/ Delay this code until complete \/
if accessToken != nil {
return accessToken
}
else {
throw SpotifyError.failedToGetAccessToken
}
// /\ /\
}

没有组,我的代码会抛出 SpotifyError.failedToGetAccessToken(access_token 为 nil)。

但是,在添加组之后,我的代码只是挂起并永远等待。我怎样才能延迟完成此代码?

我知道获取 token 没有问题,就像我删除 return 并在请求中放置打印一样,我得到了预期的结果。

如有疑问,请提问

最佳答案

不要试图使异步任务同步

为了方便起见,这是一个带有完成处理程序和自定义枚举的解决方案

enum Result {
case success(Spotify.JSONStandard), failure(Error)
}

func getAccessToken(completion: @escaping (Result)->()) {
Alamofire.request("https://accounts.spotify.com/api/token", method: .post, parameters: spotify.parameters, headers: nil).responseJSON(completionHandler: {
response in
// Check if response is valid
if let newValue = response.result.value as? Spotify.JSONStandard {
completion(.success(newValue)
} else {
completion(.failure(SpotifyError.failedToGetAccessToken))
}
})
}

并调用它

getAccessToken { result in
switch result {
case .success(let token) : // do something with the token
case .failure(let error) : // do something with the error
}
}

关于ios - 延迟任务直到完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51030029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com