gpt4 book ai didi

swift - 如何在 Swift 中等待函数调用结束

转载 作者:行者123 更新时间:2023-11-30 10:07:34 36 4
gpt4 key购买 nike

我的问题很简单,但经过多次研究和测试,我在继续流程之前未能成功等待函数结束。

示例:

print("Before stuff")
do_stuff {
print("After stuff")
}


func do_stuff(onCompleted: () -> ()) {
let postEndpoint: String = "http://localhost:8080/users/1234567890987654"
guard let url = NSURL(string: postEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(urlRequest, completionHandler: {
(data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /users/1234567890987654")
print(error)
return
}
// parse the result as JSON
let user: NSDictionary
do {
user = try NSJSONSerialization.JSONObjectWithData(responseData,
options: []) as! NSDictionary
} catch {
print("error trying to convert data to JSON")
// Means that user does not exist
return
}
print("The user is: " + user.description)
})
task.resume()
onCompleted()
}

如何在第二次打印之前等待 do_stuff() 结束?

感谢您的帮助,我想我错过了一些东西。

托马斯

最佳答案

有一些基本的东西你还没有理解。它实际上并不是正在执行的函数。它是函数内部定义的闭包。您需要等待的是请求完成后调用的闭包。事实上,您不应该等待,而是在函数外部分配另一个闭包,以便从函数内部的闭包调用。

print("Before stuff")
do_stuff {
// Now the "function" has completed.
print("After stuff")
}

func do_stuff(onCompleted: () -> ()) {
let task = session.dataTaskWithRequest(urlRequest) { data, response, error in
...
onCompleted()
}
}

关于swift - 如何在 Swift 中等待函数调用结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35210591/

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