- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试编写一个从 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/
我想了解 Ruby 方法 methods() 是如何工作的。 我尝试使用“ruby 方法”在 Google 上搜索,但这不是我需要的。 我也看过 ruby-doc.org,但我没有找到这种方法。
Test 方法 对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值指示是否找到匹配的模式。 object.Test(string) 参数 object 必选项。总是一个
Replace 方法 替换在正则表达式查找中找到的文本。 object.Replace(string1, string2) 参数 object 必选项。总是一个 RegExp 对象的名称。
Raise 方法 生成运行时错误 object.Raise(number, source, description, helpfile, helpcontext) 参数 object 应为
Execute 方法 对指定的字符串执行正则表达式搜索。 object.Execute(string) 参数 object 必选项。总是一个 RegExp 对象的名称。 string
Clear 方法 清除 Err 对象的所有属性设置。 object.Clear object 应为 Err 对象的名称。 说明 在错误处理后,使用 Clear 显式地清除 Err 对象。此
CopyFile 方法 将一个或多个文件从某位置复制到另一位置。 object.CopyFile source, destination[, overwrite] 参数 object 必选
Copy 方法 将指定的文件或文件夹从某位置复制到另一位置。 object.Copy destination[, overwrite] 参数 object 必选项。应为 File 或 F
Close 方法 关闭打开的 TextStream 文件。 object.Close object 应为 TextStream 对象的名称。 说明 下面例子举例说明如何使用 Close 方
BuildPath 方法 向现有路径后添加名称。 object.BuildPath(path, name) 参数 object 必选项。应为 FileSystemObject 对象的名称
GetFolder 方法 返回与指定的路径中某文件夹相应的 Folder 对象。 object.GetFolder(folderspec) 参数 object 必选项。应为 FileSy
GetFileName 方法 返回指定路径(不是指定驱动器路径部分)的最后一个文件或文件夹。 object.GetFileName(pathspec) 参数 object 必选项。应为
GetFile 方法 返回与指定路径中某文件相应的 File 对象。 object.GetFile(filespec) 参数 object 必选项。应为 FileSystemObject
GetExtensionName 方法 返回字符串,该字符串包含路径最后一个组成部分的扩展名。 object.GetExtensionName(path) 参数 object 必选项。应
GetDriveName 方法 返回包含指定路径中驱动器名的字符串。 object.GetDriveName(path) 参数 object 必选项。应为 FileSystemObjec
GetDrive 方法 返回与指定的路径中驱动器相对应的 Drive 对象。 object.GetDrive drivespec 参数 object 必选项。应为 FileSystemO
GetBaseName 方法 返回字符串,其中包含文件的基本名 (不带扩展名), 或者提供的路径说明中的文件夹。 object.GetBaseName(path) 参数 object 必
GetAbsolutePathName 方法 从提供的指定路径中返回完整且含义明确的路径。 object.GetAbsolutePathName(pathspec) 参数 object
FolderExists 方法 如果指定的文件夹存在,则返回 True;否则返回 False。 object.FolderExists(folderspec) 参数 object 必选项
FileExists 方法 如果指定的文件存在返回 True;否则返回 False。 object.FileExists(filespec) 参数 object 必选项。应为 FileS
我是一名优秀的程序员,十分优秀!