gpt4 book ai didi

ios - Swift 方法乱序执行,因为程序没有等待 URLSession.shared.dataTask 完成

转载 作者:搜寻专家 更新时间:2023-11-01 06:50:53 25 4
gpt4 key购买 nike

我正在尝试编写一个从 API 检索数据并随后显示在应用程序 View 中的应用程序。问题是当我运行我的代码时,设置 View 的 setupViews() 始终在检索 JSON 数据之前运行,即使我在 getJson() 函数之后调用它也是如此。 getJson() 函数首先运行,但它在“URLSession.shared.dataTask(with: the_urlObj) {(data, _,error) in ”处停止并跳过函数的其余部分,然后执行所有剩余的在程序返回之前首先运行。如何在调用 setupViews() 函数之前执行完整的 getJson() 函数?

我注意到 URLSession.shared.dataTask 行是 getJson() 函数中的代码停止的地方。在 setupViews() 函数已经执行后,它返回到该代码的其余部分。我尝试在 URLSession.shared.dataTask 行之后的 getJson() block 中调用 self.setupViews() ,但 View 仍然显示没有数据。

// viewDidLoad function

override func viewDidLoad() {
super.viewDidLoad()
getJson()
setupViews()
}

//getJson function

func getJson(){
let jsonString = "https://api.openweathermap.org/data/2.5/weather?q=brooklyn,us&APPID=f942c97cab0e663a9a4882e6c3f0db1e"
guard let url = URL(string: jsonString) else { return }
URLSession.shared.dataTask(with: url) { (data,response,err) in
guard let data = data else { return }
do {

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .secondsSince1970
let weatherData = try decoder.decode(WeatherData.self, from: data)
print("temperature: ", weatherData.main.temp)
// self.todays_weather.text = String("\(temperature)")
temperature = Int(weatherData.main.temp)
temperature = (temperature * 9/5)-459

}
catch {
print(err)
print(response)
}

}.resume()

//setup views function

func setupViews(){
self.view.addSubview(todays_weather)
todays_weather.heightAnchor.constraint(equalToConstant: 140).isActive = true
todays_weather.widthAnchor.constraint(equalToConstant: 150).isActive = true
todays_weather.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
todays_weather.centerYAnchor.constraint(equalTo: self.view.topAnchor, constant: 120).isActive = true

self.view.addSubview(weather_button)
weather_button.heightAnchor.constraint(equalToConstant: 240).isActive = true
weather_button.widthAnchor.constraint(equalToConstant: 300).isActive = true
weather_button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
weather_button.centerYAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -90).isActive = true

let todays_weather : UITextField = {
let weather = UITextField()
weather.textColor = UIColor.black
weather.textAlignment = .center
weather.text = String("\(temperature)")
weather.font = UIFont.systemFont(ofSize:32)
weather.translatesAutoresizingMaskIntoConstraints = false
return weather
}()

代码运行良好,但 View 中的文本字段显示为 0 而不是 JSON 检索的温度,因为 setupViews() 在 JSON 数据检索完成之前执行,因为 getJson() 函数在 URLSession 处停止.shared.dataTask。

虽然我在控制台中收到此通知:2019-07-29 11:44:01.060026-0400 daily_tips[46459:8017625] 从主线程访问引擎后,此应用程序正在从后台线程修改 AutoLayout 引擎。这可能会导致引擎损坏和奇怪的崩溃。

任何帮助将不胜感激,谢谢!

最佳答案

欢迎来到 StackOverflow!您的情况是 JSON 提取是异步发生的,但您在调用 getJson() 之后立即调用 setupViews()

一个好的解决方案是在 getJson() 调用中添加一个完成处理程序。

func getJson(completionHandler: () -> ()){
let jsonString = "https://api.openweathermap.org/data/2.5/weather?q=brooklyn,us&APPID=f942c97cab0e663a9a4882e6c3f0db1e"
guard let url = URL(string: jsonString) else { return }
URLSession.shared.dataTask(with: url) { (data,response,err) in
guard let data = data else { return }
do {

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .secondsSince1970
let weatherData = try decoder.decode(WeatherData.self, from: data)
print("temperature: ", weatherData.main.temp)
// self.todays_weather.text = String("\(temperature)")
temperature = Int(weatherData.main.temp)
temperature = (temperature * 9/5)-459
completionHandler()
}
catch {
print(err)
print(response)
}

}.resume()
}

然后在completionHandler中调用setupViews():

override func viewDidLoad() {
super.viewDidLoad()
getJson { [weak self] in
DispatchQueue.main.async {
self?.setupViews()
}
}
}

我建议搜索“ios 异步编程”并搜索“ios 完成处理程序”以了解更多信息。那里有很多很棒的信息,我希望这对您有所帮助。

关于ios - Swift 方法乱序执行,因为程序没有等待 URLSession.shared.dataTask 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57257516/

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