Skip to content

Instantly share code, notes, and snippets.

@benyou1969
Created September 26, 2022 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benyou1969/5b37ab0b103c7084e682174869fd21d5 to your computer and use it in GitHub Desktop.
Save benyou1969/5b37ab0b103c7084e682174869fd21d5 to your computer and use it in GitHub Desktop.
Content view swift
import SwiftUI
import MapKit
import Foundation
// MARK: - Nationality
struct Nationality: Codable {
let country: [Country]
let name: String
}
// MARK: - Country
struct Country: Codable {
let countryID: String
let probability: Double
enum CodingKeys: String, CodingKey {
case countryID = "country_id"
case probability
}
}
// MARK: - VIEW MODEL
class ViewModel: ObservableObject {
@Published var nationality: Nationality?
func fetch(name: String) {
guard let url = URL(string:
"https://api.nationalize.io?name=\(name)") else {
return print("API Error")
}
let task = URLSession.shared.dataTask(with: url) { [weak self]
data, _, error in
guard let data = data, error == nil else { return }
do {
let nationality = try
JSONDecoder().decode(Nationality.self, from: data)
DispatchQueue.main.async {
self?.nationality = nationality
}
} catch {
print(error)
}
}
task.resume()
}
}
// MARK: - View
struct ContentView: View {
@StateObject var viewModel = ViewModel()
@State private var name: String = "Ramzi"
@State var showsheet :Bool = false
var body: some View {
NavigationView{
VStack {
Spacer()
VStack{
TextField("Write your name.",text: $name)
.padding(4)
.padding()
.onSubmit {
viewModel.fetch(name: name)
}
}
Text(viewModel.nationality?.name ?? "")
.font(.largeTitle)
AsyncImage(url: URL(string: "https://countryflagsapi.com/png/\(viewModel.nationality?.country[0].countryID ?? "")"))
.cornerRadius(15)
.shadow( radius: 5)
.padding()
.onAppear {
viewModel.fetch(name: name)
}
.onTapGesture {
showsheet.toggle()
}
.sheet(isPresented: $showsheet) {
CountryMapView(countryName: countryName(countryCode: viewModel.nationality?.country[0].countryID ?? "") ?? "")
}
Spacer()
}
}
}
// this method is responsible for returning country name from country id
func countryName(countryCode: String) -> String? {
let current = Locale(identifier: "en_US")
return current.localizedString(forRegionCode: countryCode)
}
}
// MARK: - Preview
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment