【问题标题】:Swift detect json parsing detect endswift检测json解析检测结束
【发布时间】:2020-08-25 17:28:37
【问题描述】:

我正在解析某个 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 通过观察打印变为假和真,但如果我需要使用它来创建微调器,它始终为假,因为它在内部只有真。 我怎样才能使它全球化? 谢谢

【问题讨论】:

    标签: json swift swiftui


    【解决方案1】:

    除非您在闭包内有另一个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.")
            }
        }
    }
    

    您可能希望将其设置为自定义枚举,尽管使用 fetchingdonenoDatajsonError 的情况。现在,如果没有数据,您将永远不会触发重试、继续、通知用户等。当出现解码错误时也是如此。或者至少在循环的最后将标志设置为 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,所以语法可能不准确。

    【讨论】:

    • 谢谢 - 如果我使用你的建议,它确实会改变,所以实际上变量会改变,但在 ContentView(SwiftUI)中只是为了测试我是否这样做:Text(doneGettingData.description)它的假比当我更改例如强制获取新 Json 的参数之一时,它会更改为 true,并且永远不会再更改回 false 和 true。
    猜你喜欢
    • 2021-12-15
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 2011-04-27
    • 2012-10-13
    • 2012-06-22
    相关资源
    最近更新 更多