-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathListView.swift
87 lines (77 loc) · 3.11 KB
/
ListView.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// ListView.swift
// SupHealth
//
// Created by Yahia Berrada on 6/17/20.
// Copyright © 2020 Supinfo. All rights reserved.
//
import SwiftUI
//response countries
struct ResponseCountries: Codable {
var Countries: [DataModel]
}
//favorites array
var favorites: Array<DataModel> = Array()
struct ListView: View {
@State private var Countries = [DataModel]()
@State private var showFavorites = false
var body: some View {
NavigationView {
if self.showFavorites == true { // if click on the favorite toggle
if(favorites.count == 0) { // if there isn't favorites
Text("No added favorites")
.navigationBarTitle("Informations")
.navigationBarItems(trailing:
Toggle("Show Favorites Only", isOn: $showFavorites)
)
}else {
List(favorites, id: \.Country) { item in //list of favorites
NavigationLink(destination: DetailCountry(country: item)) {
HStack {
RemoteImage(url: "https://www.countryflags.io/\(item.CountryCode)/flat/64.png")
Text(item.Country)
.font(.headline)
}
}
}.navigationBarTitle("Informations")
.navigationBarItems(trailing:
Toggle("Show Favorites Only", isOn: $showFavorites)
)
}
}else { // if favorites not clicked => display all countries
List(Countries, id: \.Country) { item in
NavigationLink(destination: DetailCountry(country: item)) {
HStack {
RemoteImage(url: "https://www.countryflags.io/\(item.CountryCode)/flat/64.png")
Text(item.Country)
.font(.headline)
}
}
}.navigationBarTitle("Informations")
.navigationBarItems(trailing:
Toggle("Show Favorites Only", isOn: $showFavorites)
)
}
}.navigationViewStyle(StackNavigationViewStyle())
.onAppear(perform: loadData)
}
//api service
func loadData() {
guard let url = URL(string: api) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(ResponseCountries.self, from: data) {
DispatchQueue.main.async {
self.Countries = decodedResponse.Countries //recup les donnees
}
return
}
}
print("\(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}