I'm working on a pull-to-refresh on iOS with Swift.
I have an array with city names, cityNames = ["Chicago", "New York City"]
I implemented a pull-to-refresh to fetch temperature data from the internet. So every time I trigger the pull-to-refresh, it will go to the internet and get the temperature for each city in the cityNames
array.
Here is the code for pull-to-refresh
var weatherDetail = [Weather]()
// Pull to refresh
func refreshData() {
var cityNames = [String]()
for (index, _) in weatherDetail.enumerate() {
let info = weatherDetail[index]
cityNames.append(info.cityName)
}
print(cityNames)
weatherDetail.removeAll()
for city in cityNames {
self.forwardGeocoding(city)
}
weatherCityTable.reloadData()
refreshControl.endRefreshing()
}
In the code above, weatherDetail
is a array of model(I'm not sure how to phrase this, but Weather
is a model, which contains city names, temperature, sun rise time, high/low temperature.forwardGeocoding
is a function that get the geo coordination for a city then sends a request to get the weather data for that city.
The pull-to-refresh works, the issue I'm encountering is, for the first 2,3 times when I pull, it works with no problem. But as I pull more times, the array will suddenly change to cityNames = ["Chicago", "Chicago"]
Thank you for your help, please let me know if you need more information.
UPDATE:
I removed weatherDetail.removeAll()
, try to just append the same data to the array. After the refresh, it prints out "Chicago", "New York City", "Chicago", "Chicago"
. If I refresh it more times, it prints out something like "Chicago", "New York City", "Chicago", "Chicago", "Chicago", "Chicago"
Is forwardGeocoding synchronous? When does weatherDetail get set/updated?
It looks to me like you have some sort of synchronicity issue going on here, probably exacerbated by latency.
Using enumerate()
and append()
to do this is not a good approach ,there is a more elegance and error-proof way to achieve this:
let cityNames:[String] = weatherDetail.map { weather -> String in
weather.cityName
}
Or just write:
let cityNames:[String] = weatherDetail.map { $0.cityName }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With