如何解决Swift检测JSON解析检测结束
我正在解析某个json url数据以绘制在地图中,因此我需要检测到我有所有数据在没有任何变化的情况下显示微调器。我创建了一个变量,当我拥有所有数据后,该变量从false变为true,但是该变量仅在for循环内以true存在。 这是获取数据的代码的一部分
import SwiftUI
import MapKit
var locationsFillTest : Int = 0
var allLocations = [MKPointAnnotation]()
var doneGettingData : Bool = false
struct MapView: UIViewRepresentable {
var startdate : String
func makeUIView(context: Context) -> MKMapView{
MKMapView(frame: .zero)
}
func makeCoordinator() -> MapViewCoordinator{
MapViewCoordinator(self)
}
func updateUIView(_ uiView: MKMapView,context: Context){
uiView.removeAnnotations(allLocations)
allLocations = []
doneGettingData = false
print("Done = \(doneGettingData)")
let url = URL(string: "https://XXXXXX")!
URLSession.shared.dataTask(with: url) {(data,response,error) in
do {
if let d = data {
let decodedLists = try JSONDecoder().decode(emsc.self,from: d)
DispatchQueue.main.async {
locationsFillTest = allLocations.count
doneGettingData = false
for locations in decodedLists.features {
let lat = Double(locations.properties.lat)
let long = Double(locations.properties.lon)
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: lat,longitude: long )
if locationsFillTest == 0 {
allLocations.append(annotation)}
}
uiView.addAnnotations(allLocations)
uiView.delegate = context.coordinator
uiView.showAnnotations(allLocations,animated: true)
doneGettingData = true
print("Done = \(doneGettingData)")
}
}else {
print("No Data")
}
} catch {
print("Error decoding JSON: ",error,response!)
}
}.resume()
}
}
通过查看打印内容,变量doneGettingData变为false和true,但是如果例如我需要使用它来创建一个微调器,则因为它的唯一内部值始终为false。 我如何使其全球化? 谢谢
解决方法
除非您在闭包内部另外有doneGettingData
的声明,否则实例级别属性将设置为true。虽然可能设置得比您预期的晚。尝试以下操作以查看其更改时间(并使您设置为对这些更改做出反应):
var doneGettingData : Bool = false {
didSet {
if doneGettingData {
print("The instance property doneGettingData is now true.")
} else {
print("The instance property doneGettingData is now false.")
}
}
}
尽管使用fetching
,done
,noData
和jsonError
这样的案例,您可能希望将其设置为自定义枚举。现在,如果没有数据,您将永远不会有重试,继续前进,通知用户等的触发器。当存在解码错误时,同样适用。或者至少在循环的最后将标志设置为true,这样无论发生什么事情都会发生。
类似的东西:
enum DataCollectionState {
case fetching,done,noData,jsonError
var doneGettingData : DataCollectionState = fetching {
didSet {
switch doneGettingData {
case fetching:
// Show a spinner or something
case done:
// Hide the spinner
case noData:
// Tell the user there was no data? Try again?
case jsonError:
// Tell the user there was an error? Try again?
}
}
}
注意:我现在没有打开Xcode,因此语法可能不正确。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。