-
Notifications
You must be signed in to change notification settings - Fork 3
/
ContentView.swift
59 lines (48 loc) · 1.61 KB
/
ContentView.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// ContentView.swift
// X06 Friends
//
// Created by Julian Moorhouse on 04/04/2021.
//
import SwiftUI
import CoreData
struct ContentView: View {
// @Environment(\.managedObjectContext) var moc
@State var users = [User]()
var body: some View {
NavigationView {
List(users) { user in
NavigationLink(destination: DetailView(user: user, users: users)) {
Text(user.name)
}
}
.onAppear(perform: loadData)
.navigationBarTitle("Friends")
}
}
func loadData() {
guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
if let decodedResponse = try? decoder.decode([User].self, from: data) {
DispatchQueue.main.async {
self.users = decodedResponse
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()//.environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
}