ios - 在 API 完成写入数组之前,Swift 读取和创建数组的速度太快了
问题描述
我正在练习 DispatchQueue 并且整天都在挣扎,因为在 API 完成写入数组之前,swift 太快了。我注意到以下两个不同的代码:
fetchingSunServer() // Start call the API to get sunrise and sunset time list
DispatchQueue.main.asyncAfter(deadline: .now() + 3, execute: {
print("\(sunrisesunsetString.count)\n\(sunrisesunset1970.count)\nFinished create data.")
})
// Will return the result:
// 4
// 4
// Finished create data.
这很好,如果在 3 秒后等待,我就能够从该数组中获取信息。
但是,我认为上面的这段代码是不专业的,因为有时如果 API 很慢并且在 3 秒后还没有准备好怎么办,所以我尝试以专业的方式。这是我的代码:
在 ViewController.swift 中
let fetchingSunriseSunset = DispatchGroup()
fetchingSunriseSunset.enter()
DispatchQueue.main.async {
fetchingSunServer() // Start call the API to get sunrise and sunset time list
fetchingSunriseSunset.leave()
}
fetchingSunriseSunset.notify(queue: .main) {
print("\(sunrisesunsetString.count)\n\(sunrisesunset1970.count)\nFinished create data.")
}
// Will return the result:
// 0
// 0
// Finished create data.
两个数组都返回零,因为 API 没有完成,我怎样才能让打印等到 API 完成将太阳时间信息插入数组?
更新:这里的代码来自 fetchingSunServer()
if let url = URL(string: "https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&formatted=0") {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
do {
let res = try JSONDecoder().decode(Response.self, from: data)
let dateAPI = DateFormatter()
dateAPI.locale = Locale(identifier: "en_US_POSIX")
dateAPI.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let ss_rise_ast = dateAPI.date(from: res.results.astronomical_twilight_begin)
let ss_rise_nau = dateAPI.date(from: res.results.nautical_twilight_begin)
let ss_rise_civ = dateAPI.date(from: res.results.civil_twilight_begin)
let ss_sunrise = dateAPI.date(from: res.results.sunrise)
let ss_solar = dateAPI.date(from: res.results.solar_noon)
let ss_sunset = dateAPI.date(from: res.results.sunset)
let ss_set_civ = dateAPI.date(from: res.results.civil_twilight_end)
let ss_sun_nau = dateAPI.date(from: res.results.nautical_twilight_end)
let ss_sun_ast = dateAPI.date(from: res.results.astronomical_twilight_end)
let dateToString = DateFormatter()
dateToString.dateFormat = "h:mm a"
let resultDate_ss_rise_ast = dateToString.string(from: ss_rise_ast!)
let resultDate_ss_rise_nau = dateToString.string(from: ss_rise_nau!)
let resultDate_ss_rise_civ = dateToString.string(from: ss_rise_civ!)
let resultDate_ss_sunrise = dateToString.string(from: ss_sunrise!)
let resultDate_ss_solar = dateToString.string(from: ss_solar!)
let resultDate_ss_sunset = dateToString.string(from: ss_sunset!)
let resultDate_ss_set_civ = dateToString.string(from: ss_set_civ!)
let resultDate_ss_sun_nau = dateToString.string(from: ss_sun_nau!)
let resultDate_ss_sun_ast = dateToString.string(from: ss_sun_ast!)
if res.status == "OK" {
self.sunrisesunsetString = [(
ss_rise_ast: resultDate_ss_rise_ast,
ss_rise_nau: resultDate_ss_rise_nau,
ss_rise_civ: resultDate_ss_rise_civ,
ss_sunrise: resultDate_ss_sunrise,
ss_solar: resultDate_ss_solar,
ss_sunset: resultDate_ss_sunset,
ss_set_civ: resultDate_ss_set_civ,
ss_sun_nau: resultDate_ss_sun_nau,
ss_sun_ast: resultDate_ss_sun_ast,
ss_timeday: res.results.day_length)]
self.sunrisesunset1970 = [(
ss_rise_ast: ss_rise_ast!.timeIntervalSince1970,
ss_rise_nau: ss_rise_nau!.timeIntervalSince1970,
ss_rise_civ: ss_rise_civ!.timeIntervalSince1970,
ss_sunrise: ss_sunrise!.timeIntervalSince1970,
ss_solar: ss_solar!.timeIntervalSince1970,
ss_sunset: ss_sunset!.timeIntervalSince1970,
ss_set_civ: ss_set_civ!.timeIntervalSince1970,
ss_sun_nau: ss_sun_nau!.timeIntervalSince1970,
ss_sun_ast: ss_sun_ast!.timeIntervalSince1970)]
self.fetchingSunriseSunset.leave()
} else {
print("Error received API from Sunrise and Sunset")
self.fetchingSunriseSunset.leave()
}
} catch let error {
print(error)
self.fetchingSunriseSunset.leave()
}
}
}.resume()
}
}
解决方案
您可以像这样更改“fetchingSunServer”方法的实现:
func fetchingSunServer(completion: @escaping (() -> Void)) {
//// Your code for fetching the data and after getting the data from server
completion()
}
你的实现将是这样的:
self.fetchingSunServer {
DispatchQueue.main.async {
print("\(sunrisesunsetString.count)\n\(sunrisesunset1970.count)\nFinished create data.")
}
}
那么你不必DispatchGroup
在这种情况下使用。
推荐阅读
- r - 如何在不打开 R 或 RStudio 的情况下运行 R 脚本?
- javascript - How to handle mutliple responses using Promise.all if one promise fails?
- java - 尝试使用枚举中的值对其进行初始化时,我有一个空数组列表
- php - pg_prepare problem with string parameters
- ios - Giving the option of saving the same data over again,
- javascript - Loop through inputs and add them
- mongodb - MongoDB search with colon in field name
- react-native - React-Native 和 Redux:如何重用 reducer 来处理多个组件
- android - Why is my notification listener service not starting?
- python - Pandas:过去 k 天的平均值