Ios 延迟任务直到完成

Ios 延迟任务直到完成,ios,swift,Ios,Swift,人们经常会问“如何延迟一个函数或一段代码?”但这不是我需要的 我需要我的代码等待某个任务完成,否则我的函数会收到一个错误,即我没有访问权\u令牌(因为代码不会等待从Spotify服务器获取数据) 以下是我迄今为止的代码,尝试添加: func getAccessToken()抛出->Spotify.json标准{ var accessToken:Spotify.JSONStandard! 让group=DispatchGroup()//不要尝试使异步任务同步 为了方便起见,这是一个带有完成处理程序

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

我需要我的代码等待某个任务完成,否则我的函数会收到一个错误,即我没有访问权\u令牌(因为代码不会等待从Spotify服务器获取数据)

以下是我迄今为止的代码,尝试添加:

func getAccessToken()抛出->Spotify.json标准{
var accessToken:Spotify.JSONStandard!

让group=DispatchGroup()//不要尝试使异步任务同步

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

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
   }
}

不要尝试使异步任务同步

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

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
   }
}

不要等待,通知。你的方法是错误的。
DispatchGroup
API用于在一个循环中同步多个异步任务。你必须编写一个完成处理程序。请学习理解异步数据处理。@vadian我该如何做一个完成处理程序?你能发送一个链接或一段代码吗?我写了一个答案。不要它,notify。你的方法是错误的。
DispatchGroup
API用于在循环中同步多个异步任务。你必须编写一个完成处理程序。请学习理解异步数据处理。@vadian我该如何做一个完成处理程序?你能发送一个链接或一段代码吗?我写了一个答案。键入somet吗很相似。这真是一个很好的解决方案。我输入了类似的东西。这真是一个很好的解决方案。