ContentView.swift
//
// ContentView.swift
// JongjuAR
//
// Created by 전민정 on 6/6/22.
//
import SwiftUI
struct ContentView: View {
@ObservedObject var datas = ReadData()
var body: some View {
NavigationView {
List(datas.jongjus) { jongju in
Section(header: Text(jongju.name)) {
ForEach(jongju.routes) { route in
NavigationLink(destination: DownloadGPXView(route: route)) {
Text(route.name)
}
}
}
}
}
}
}
struct DownloadGPXView: View {
var route: Route
init(route: Route) {
self.route = route
}
var body: some View {
List {
ForEach(route.courses) { course in
Text(course.name)
}
}
}
}
class ReadData: ObservableObject {
@Published var jongjus = [Jongju]()
init() {
loadData()
}
func loadData() {
guard let url = Bundle.main.url(forResource: "Backdu", withExtension: "json") else {
print("json not found...")
return
}
let data = try? Data(contentsOf: url)
do {
let jongjus = try JSONDecoder().decode([Jongju].self, from: data!)
self.jongjus = jongjus
} catch {
print(error)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Model.swift
//
// Model.swift
// JongjuAR
//
// Created by 전민정 on 6/8/22.
//
import Foundation
struct Course : Codable, Identifiable {
enum CodingKeys: CodingKey {
case num
case name
case mmap
case gpx
}
var id = UUID()
var num: Int
var name: String
var mmap: String
var gpx: String
}
struct Route : Codable, Identifiable {
enum CodingKeys: CodingKey {
case num
case name
case courseType
case courseCnt
case courses
}
var id = UUID()
var num: Int
var name: String
var courseType: String
var courseCnt: Int
var courses: [Course]
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
num = try values.decode(Int.self, forKey: .num)
name = try values.decode(String.self, forKey: .name)
courseType = try values.decode(String.self, forKey: .courseType)
courseCnt = try values.decode(Int.self, forKey: .courseCnt)
courses = try values.decode([Course].self, forKey: .courses)
}
}
struct Jongju : Identifiable, Codable {
enum CodingKeys: CodingKey {
case name
case routes
}
var id = UUID()
var name: String // 백두대간
var routes: [Route]
}
Backdu.json 일부
[{
"name": "백두대간",
"routes": [
{
"num": 1,
"name": "지리산권",
"courseType": "종주",
"courseCnt": 7,
"courses": [
{
"num": 1,
"name": "천왕봉-세석산장",
"mmap": "",
"gpx": "백두대간_지리산권_종주_1코스.gpx"
},
{
"num": 2,
"name": "세석산장-토끼봉",
"mmap": "",
"gpx": "백두대간_지리산권_종주_2코스.gpx"
},
{
"num": 3,
"name": "토끼봉-헬기장",
"mmap": "",
"gpx": "백두대간_지리산권_종주_3코스.gpx"
},
References
https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/JSON
https://jinnify.tistory.com/71
https://discourse.codershigh.com/t/codable/454
https://medium.com/@nutanbhogendrasharma/read-json-data-from-file-system-in-swiftui-d054662000e
https://www.hohyeonmoon.com/blog/swiftui-tutorial-navigation/
728x90
반응형
'개발 > JongjuAR' 카테고리의 다른 글
FileDownload in swift (0) | 2022.06.10 |
---|---|
Pod 설치 (0) | 2022.06.06 |