100 days of swiftui: Milestone: Projects 10-12
It’s time for you to build an app from scratch, and it’s a particularly expansive challenge today: your job is to use URLSession to download some JSON from the internet, use Codable to convert it to Swift types, then use NavigationStack, List, and more to display it to the user.
Your first step should be to examine the JSON. The URL you want to use is this: https://www.hackingwithswift.com/samples/friendface.json – that’s a massive collection of randomly generated data for example users.
As you can see, there is an array of people, and each person has an ID, name, age, email address, and more. They also have an array of tag strings, and an array of friends, where each friend has a name and ID.
How far you implement this is down to you, but at the very least you should:
If you’re not sure where to begin, start by designing your types: build a User struct with properties for name, age, company, and so on, then a Friend struct with id and name. After that, move onto some URLSession code to fetch the data and decode it into your types.
You might notice that the date each user registered has a very specific format: 2015-11-10T01:47:18-00:00. This is known as ISO-8601, and is so common that there’s a built-in dateDecodingStrategy called .iso8601 that decodes it automatically.
While you’re building this, I want you to keep one thing in mind: this kind of app is the bread and butter of iOS app development – if you can nail this with confidence, you’re well on your way to a full-time job as an app developer.
Tip: As always, the best way to solve this challenge is to keep it simple – write as little code as you can to solve the challenge, and for you to feel comfortable that it works well.
URLSession을 사용해서 인터넷에서 JSON을 다운받고, Codable을 사용해서 swift의 타입으로 전환시키고, user를 나타내기 위해 NavigationStack, List 등을 사용해야 한다.
import Foundation
struct User: Codable {
var id: String
var isActive: Bool
var name: String
var age: Int
var company: String
var email: String
var address: String
var about: String
var registered: String
var tags: [String]
var friends: [Friend]
}
struct Friend: Codable {
var id: String
var name: String
}
json 파일을 살펴 Codable 프로토콜을 만족하는 struct를 생성했다.
그리고 json 파일(https://www.hackingwithswift.com/samples/friendface.json)에서 데이터를 불러와 [User]타입인 users에 저장하도록 했다. json 파일을 보면 사용자들의 배열인 것을 확인할 수 있는데, 이를 참고해 [User]로 decode하게 설정했다.
List 대신 Grid로 사용자들의 이름을 나타내었다. 그리고 isActive
가 true이면 이름의 오른쪽 위에 파란 점으로 표시했다.
정보를 label로 간단하게 나열했다.
데이터를 불러올 때 users가 존재하는지 확인하는 코드를 추가했다.
func loadUsers() async {
print("load users: start")
// 0: check existing users
if !users.isEmpty {
return
}
// ...