포스트

7주차 과제 (2)

API로 부터 값 가져오기.

어떤 값이 필요로할지 조건을 보고 다음과 같이 모델링을 해두었다.

1
2
3
4
5
6
7
8
9
10
struct DataModel {
    
    let id: Int
    let title: String
    let description: String
    let price: Int
    let discountPercentage: Double
    let thumbnail: String
    
}

image의 경우 url이기에 아무래도 3rd Party Library를 사용해야 할 것 같다.

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
 func fetchRequest() {
        
        var pageNumber: Int = 1
        
        let url = "https://dummyjson.com/products/\(pageNumber)"
        
        if let url = URL(string: url) {
 
            let urlSession = URLSession(configuration: .default)
            
            let task = urlSession.dataTask(with: url) { (data,response,error) in
                
                if error != nil {
                    print(error?.localizedDescription)
                    return
                }
                
                if let safeData = data {
                    print(safeData)
                }
            }
            
            task.resume()
        }

    }

우선 다음과 같이 적었다

첨에 왜 결과값이 안보이나 했는데 task.resume()을 빼먹었다.

출력결과 537bytes가 나온다.

즉 Decoding을 해야한다는 뜻이다.

Decoder 함수 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func decodingJson (data: Data) -> [DataModel]? {
        
        let decoder = JSONDecoder()
        do {
            let decodedData = try decoder.decode(DataModel.self, from: data)
            let id = decodedData.id
            let title = decodedData.title
            let description = decodedData.description
            let price = decodedData.price
            let discountPercentage = decodedData.discountPercentage
            let thumnail = decodedData.thumbnail
            
            var list: [DataModel] = [DataModel(id: id, title: title, description: description, price: price, discountPercentage: discountPercentage, thumbnail: thumnail)]
          
            return list
            
        } catch {
            print(error)
            
            return []
        }
            
    }

그리고 해당부분을 확인하기 위해 우선 프린트로 대체했다

1
2
3
4
if let safeData = data {
                    let decodedData = self.decodingJson(data: safeData)
                    print(decodedData)
                }

출력해보니 잘 나온다.

UI에 값 구현하기.

잘나오는 것을 확인했으니 이제 값을 전달하기 위해 Delegate를 사용하여 전달한다.

인터넷 찾아보니 cocoapod을 안해도 url로 이미지를 가져올수있어서 그걸 사용하기로 했다.

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
extension ViewController: SendData {
    func sendList(data: [DataModel]) {
        list = data
        
        DispatchQueue.main.async {
            self.imageView.load(url: URL(string: self.list[0].thumbnail)!)
            self.titleLabel.text = self.list[0].title
            self.bodyLabel.text = self.list[0].description
            self.priceLabel.text = self.numberFormatter.string(from: Double(self.list[0].price) * self.list[0].discountPercentage as NSNumber)
        }
    }   
}

extension UIImageView {
    func load(url: URL) {
        DispatchQueue.global().async { [weak self] in
            if let data = try? Data(contentsOf: url) {
                if let image = UIImage(data: data) {
                    DispatchQueue.main.async {
                        self?.image = image
                    }
                }
            }
        }
    }
}

실행하면?

Apr-10-2024 16-27-58

우선 api로 값을 UI에 띄우는것 까지는 구현이 되었다.

다음글에서는 CoreData를 활용하여 위시리스트를 담아보도록 하겠다.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.