gpt4 book ai didi

swift - iOS 中的 Collection View

转载 作者:可可西里 更新时间:2023-11-01 01:57:01 25 4
gpt4 key购买 nike

我试图使用 swift 4 和 openWeather API 构建一个天气应用程序,但我被困在这个函数中:

func fetchWeather(){
let weatherGetter = GetWeather()
self.cityWeather = [Temperature]()
for city in cities {
weatherGetter.getWeather(city: city) { (temp) in
guard let temp = temp else {return}
print(temp)
self.cityWeather?.append(temp)
}
}
print(self.cityWeather?.count)
self.collectionView?.reloadData()
}

所以这个函数在控制台中给了我这个

Optional(0) Temperature(city: "London", cityTemperature: "294.06", tempIcon: "01d") Temperature(city: "Tokyo", cityTemperature: "297.33", tempIcon: "09n") Temperature(city: "Paris", cityTemperature: "298.0", tempIcon: "01d") Temperature(city: "Moscow", cityTemperature: "291.41", tempIcon: "01n")

这对我来说真的很奇怪,因为 print(self.cityWeather?.count) 在 for 循环之后使用,但在控制台中 Optional(0) 排在第一位。

所以如果我使用这个方法

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cityWeather?.count ?? 0
}

我的 Collection View 单元格不会显示,因为它返回 0。

但是如果在 self.cityWeather?.append(temp) 之后使用 print(self.cityWeather) 我明白了! (我删除的所有其他打印语句):

Optional([WhatsWeather.Temperature(city: "Moscow", cityTemperature: "291.41", tempIcon: "01n")]) Optional([WhatsWeather.Temperature(city: "Moscow", cityTemperature: "291.41", tempIcon: "01n"), WhatsWeather.Temperature(city: "London", cityTemperature: "294.05", tempIcon: "01d")]) Optional([WhatsWeather.Temperature(city: "Moscow", cityTemperature: "291.41", tempIcon: "01n"), WhatsWeather.Temperature(city: "London", cityTemperature: "294.05", tempIcon: "01d"), WhatsWeather.Temperature(city: "Paris", cityTemperature: "298.0", tempIcon: "01d")]) Optional([WhatsWeather.Temperature(city: "Moscow", cityTemperature: "291.41", tempIcon: "01n"), WhatsWeather.Temperature(city: "London", cityTemperature: "294.05", tempIcon: "01d"), WhatsWeather.Temperature(city: "Paris", cityTemperature: "298.0", tempIcon: "01d"), WhatsWeather.Temperature(city: "Tokyo", cityTemperature: "297.38", tempIcon: "09n")])

最佳答案

只有在所有城市数据都存储在您的数据源中后,您才应该重新加载 collectionView,因为这是一个 API 调用,接收每个响应都需要时间。因此,您应该做的是在完成内部检查是否已收到所有数据,然后重新加载 collectionView

func fetchWeather(){
let weatherGetter = GetWeather()
self.cityWeather = [Temperature]()
var networkCallsDone = 0
for city in cities {
weatherGetter.getWeather(city: city) { (temp) in
networkCallsDone += 1
guard let temp = temp else {
if networkCallsDone == cities.count {
DispatchQueue.main.async {
collectionView.reloadData() //In case the last network call to finish does not return valid data
}
}
return
}
print(temp)
self.cityWeather?.append(temp)
if networkCallsDone == cities.count {
DispatchQueue.main.async {
collectionView.reloadData()
}
}
}
}
}

编辑:感谢 matt 在检查 count 和线程问题时指出逻辑错误。

关于swift - iOS 中的 Collection View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51753416/

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