
🩵 오늘 한 것
✔️ ARC 무한 복습 & 네트워크 통신
ARC는 진짜 스위프트의 꽃인듯 하다... 어쩜 이렇게 조금만 파면 ARC로 귀결되는지?ㅋㅋㅋ
와중에 오늘 챌린지반 세션에서 비소유 참조에 관해서 조금 깊은 이야기가 나와서 그걸 정리하던 중,
아 이거 오늘로 못끝낸다.. 하고 내일로 미루었다.
새로 지급된 강의에 네트워크 통신이 있었는데, 이 부분이 재밌으면서도 어려웠다.
우선 디코딩 하는 부분만 학습했는데 (이거 말고 아직은 뭘 더 쓸 것 같지 않아서..) 와 진짜 어렵다
관련부분 포스팅
: https://yy-dev.tistory.com/116
: https://yy-dev.tistory.com/117
[Swift] 네트워크 통신(1) - URL과 REST API
🩵 URL URL은 웹 상에 존재하는 자원의 위치를 가리키는 주소입니다. 자원은 문서, 이미지, 동영상 등 어떤 것이든 될 수 있어요. URL은 특정 자원에 대한 요청을 식별하고 전달하는 데 사용됩니다.
yy-dev.tistory.com
// MARK: - JSON 데이터와 Swift 객체 간의 이름이 다를 때 CodingKeys를 사용하여 이름을 매핑해주는 것은 일반적인 디코딩 작업에서 자주 사용되는 패턴
struct Product: Decodable {
    
    // MARK: 프로퍼티 정의
    
    let key: Int // 원래는 id 인데 이름을 key 로 바꿔봄 (1)
    let productTitle: String // 원래는 title 인데 이름을 productTitle 로 바꿔봄 (1)
    let description: String
    let price: Int
    let discountPercentage: Double
    let rating: Double
    let stock: Int
    let brand: String
    let category: String
    let thumbnail: String
    let images: [String]
    
    // MARK: CodingKeys 열거형
    //      프로퍼티의 이름과 실제 JSON 데이터의 키를 매핑하는 역할
    //      이를 통해 Swift에서 다른 이름의 프로퍼티를 사용하고 JSON에서 원하는 이름으로 디코딩할 수 있음
    
    public enum CodingKeys: String, CodingKey {
        case key = "id" // 원래는 id 인데 이름을 key 로 바꿔봄 (2)
        case productTitle = "title" // 원래는 title 인데 이름을 productTitle 로 바꿔봄 (2)
        case description
        case price
        case discountPercentage
        case rating
        case stock
        case brand
        case category
        case thumbnail
        case images
    }
    
    // MARK: init(from decoder:) 초기화 메소드
    //      Decodable 프로토콜을 따르는 객체를 생성하기 위해 init(from:) 초기화 메소드 구현
    //      각 프로퍼티를 디코딩하기 위해 container를 사용하고, CodingKeys를 통해 매핑된 키를 지정하여 디코딩
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        key = try container.decode(Int.self, forKey: .key) // 원래는 id 인데 이름을 key 로 바꿔봄 (3)
        productTitle = try container.decode(String.self, forKey: .productTitle) // 원래는 title 인데 이름을 productTitle 로 바꿔봄 (3)
        description = try container.decode(String.self, forKey: .description)
        price = try container.decode(Int.self, forKey: .price)
        discountPercentage = try container.decode(Double.self, forKey: .discountPercentage)
        rating = try container.decode(Double.self, forKey: .rating)
        stock = try container.decode(Int.self, forKey: .stock)
        brand = try container.decode(String.self, forKey: .brand)
        category = try container.decode(String.self, forKey: .category)
        thumbnail = try container.decode(String.self, forKey: .thumbnail)
        images = try container.decode([String].self, forKey: .images)
    }
}
override func viewDidLoad() {
        super.viewDidLoad()
        SkeletonUI()
        decodeing()
    }
    
    func SkeletonUI() {
        titleLabel.text = "show Skeleton"
        descriptionLabel.text = "show Skeleton"
    }
    func decodeing() {
        if let url = URL(string: "https://dummyjson.com/products/\(productID)") {
            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
                
                if let error = error  {
                    print("Error: \(error)")
                } else if let data = data {
                    do {
                        let product = try JSONDecoder().decode(Product.self, from: data)
                        
                        // 네트워크 요청이 완료되고 상품 정보가 성공적으로 디코딩되면 호출되는 부분
                        // 실제 데이터로 UI를 업데이트
                        DispatchQueue.main.async {
                            self.updateUIWithProduct(product)
                        }
                        
                        print("Decoded Product:")
                        print("ID: \(product.key)") // 원래는 id 인데 이름을 key 로 바꿔봄 (4)
                        print("Title: \(product.productTitle)") // 원래는 title 인데 이름을 productTitle 로 바꿔봄 (4)
                        print("Description: \(product.description)")
                        print("Price: \(product.price)")
                        print("Discount Percentage: \(product.discountPercentage)")
                        print("Rating: \(product.rating)")
                        print("Stock: \(product.stock)")
                        print("Brand: \(product.brand)")
                        print("Category: \(product.category)")
                        print("Thumbnail: \(product.thumbnail) \(type(of: product.thumbnail))")
                        print("Images: \(product.images)")
                    } catch {
                        print("Decode Error: \(error)")
                    }
                }
            }
            
            task.resume()
        }
    }
개인과제 요구사항 중에 스켈레톤을 사용하라는 부분이 있어서 그게 어디서 동작되는 부분인지도 공부해봤다.
URLSession을 사용한 데이터 요청이 시작되기 전에 우선 스켈레톤 화면을 띄우고 있는다.
그 뒤 데이터 응답을 받아오면 self.updateUIWithProduct(product) 로 label 내용을 업데이트 해준다.
이미지 url 관련해서 사용하는 방법도 내일 포스팅을...^^
세션만 들으면 시간이 없어서 저녁에 뭘 못한다. 그래도 유익한 세션이라.. 즐겁게 듣는중ㅎㅎ
✔️ 또 팀장이 됨

오늘은 새로운 팀을 만났다! 처음으로 5인팀이 구성되었다.
그런데 만나서 인사하고 눈 감았다 뜨니까 팀장이 되어있었다. 이게 뭥미.
이왕 하게 된 거 열심히는 해보겠다만 다음 번에는 꼭 팀원을 해볼 수 있기를..ㅋㅋ
'TIL' 카테고리의 다른 글
| [WIL] 24.01.05 - 24.01.23 (1) | 2024.01.23 | 
|---|---|
| [TIL] 24.01.04 (0) | 2024.01.04 | 
| [TIL] 24.01.02 (2) | 2024.01.02 | 
| [TIL] 23.12.27 (1) | 2023.12.27 | 
| [TIL] 23.12.21 (1) | 2023.12.21 |