true is set to isJsonToLoad when Button get pressed:
Button(action: {
showDocumentPicker = true
isJsonToLoad = true // <----
}){ Text("Load JSON schema").padding() }
but here it is not active yet, so if statement will not be triggered. Why it is not true?
}.sheet(isPresented: self.$showDocumentPicker) {
if isJsonToLoad { // <----
DocumentPicker(filePath: $jsonURL)
} else if isJsonSchemaToLoad {
DocumentPicker(filePath: $jsonSchemaURL)
}
}
and some more code:
import SwiftUI
import JSONSchema
struct ContentView: View {
var d1: [String: Any]? = nil
var res: ValidationResult?
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.json])
@State private var showDocumentPicker = false
@State private var isJsonToLoad = false
@State private var isJsonSchemaToLoad = false
@State private var jsonURL = URL(string: "")
@State private var jsonSchemaURL = URL(string: "")
init() {
updateValue()
return
}
mutating func updateValue() {
do {
if let jsonURL = Bundle.main.url(forResource: "user", withExtension: "json") {
let jsonData = try Data(contentsOf: jsonURL)
let d = try JSONSerialization.jsonObject(with: jsonData)
res = try JSONSchema.validate(d, schema: [
"type": "object",
"properties": [
"name": ["type": "string"],
"price": ["type": "number"],
],
"required": ["name"],
])
d1 = d as? [String: Any]
}
} catch {
}
}
func showNode(json: [String: Any], depth: Int = 1) -> AnyView {
return AnyView(VStack {
ForEach(json.keys.sorted(), id: \.self) { k in
if let str = json[k] as? String {
Text("\(k) \(str)").padding()
} else if let i = json[k] as? Int {
Text("\(k) \(i)").padding()
} else if let d2 = json[k] as? [String: Any] {
Text("\(k)").padding()
showNode(json: d2)
}
}
})
}
var body: some View {
VStack {
Button(action: {
showDocumentPicker = true
isJsonToLoad = true
}){ Text("Load JSON schema").padding() }
Button(action: {
showDocumentPicker = true
isJsonSchemaToLoad = true
}){ Text("Load JSON").padding() }
Text("\(res?.errors != nil ? "Invalid XML" : "Valid XML")")
.padding()
Divider()
Text("\(self.jsonURL?.absoluteString.description ?? "")")
.padding()
Divider()
Text("\(self.jsonSchemaURL?.absoluteString.description ?? "")")
.padding()
Divider()
if let d1 = self.d1 {
showNode(json: d1)
}
}.sheet(isPresented: self.$showDocumentPicker) {
if isJsonToLoad {
DocumentPicker(filePath: $jsonURL)
} else if isJsonSchemaToLoad {
DocumentPicker(filePath: $jsonSchemaURL)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}