简体   繁体   English

Swift - 异步/等待不停止让任务完成

[英]Swift - Async/Await not stopping to let task finish

I'm writing a simple program designed to talk to a server, get some information, and display it.我正在编写一个简单的程序,旨在与服务器对话、获取一些信息并显示它。 However, I'm running into issues with the async code, mainly that the code isn't stopping to allow the server to respond before continuing.但是,我遇到了异步代码的问题,主要是代码没有停止以允许服务器在继续之前做出响应。

I know I have to be doing something wrong but have no idea what, any help is appreciated.我知道我必须做错事但不知道是什么,感谢您的帮助。

override func viewDidLoad() {
    super.viewDidLoad()
    Task{
        let accessToken = await getToken()
    }
    print("Done")
}

private func getToken() async -> String{
    let url = URL(string: "https://api.petfinder.com/v2/oauth2/token")
    let payload = "grant_type=client_credentials&client_id=GUQj1MdQN3QunoxXz4vdd0DHPlcJC6yuqCLCEXavriJ4W6wTYV&client_secret=7whgSG3ZX6m9Cwfr2vEakOH90fSn3g0isIlae0CC".data(using: .utf8)
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    request.httpBody = payload

    do{
        let (data,_) = try await URLSession.shared.data(for: request)
        let APItoken: token = try! JSONDecoder().decode(token.self, from: data)
        return APItoken.access_token
    }
    catch{
        return ""
    }
}

If I understood the problem, you see "Done" being printed before the getToken() method is completed, right?如果我理解这个问题,您会看到在getToken()方法完成之前打印了“Done”,对吗?

The problem is that print("Done") is outside of the Task .问题是print("Done")Task之外。

When you call Task , it starts running what's in the closure and it immediately resumes after the closure, while your task is running in parallel, without blocking the main thread.当您调用Task时,它开始运行闭包中的内容,并在闭包后立即恢复,同时您的任务并行运行,而不会阻塞主线程。

Place your print() inside the Task closure, right after the getToken() method, and you'll see that it'll be "Done" after you complete your POST request.print()放在Task闭包中,就在getToken()方法之后,您会看到在完成 POST 请求后它会“完成”。

    Task{
        let accessToken = await getToken()
        print("Done")
    }

Await does not completely block your code, instead the thread that makes the call can be used to do something else, like get more user input, execute other task content that was waiting for a result and now has it. Await 不会完全阻塞您的代码,相反,发出调用的线程可用于执行其他操作,例如获取更多用户输入、执行其他正在等待结果且现在已获得结果的任务内容。 think like closure call backs, everything after the await, will be executed later, probable up to the enclosing task.像闭包回调一样思考,等待之后的所有内容都将在稍后执行,可能会执行到封闭任务。 Print(“done”) is not in your task, so it's not required to wait for the code in the task execute, the task content is probable executing in another thread, as it doesn't contain code that has to execute in the main thread. Print(“done”) 不在你的任务中,所以不需要等待任务中的代码执行,任务内容很可能在另一个线程中执行,因为它不包含必须在主线程中执行的代码线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM