[ios/swift] URLSession으로 API데이터 가져오기

2022. 12. 24. 01:10IOS

URLSession으로 Punk API 데이터를 가져오려고 한다! 먼저 Punk API를 살펴보자.

 

https://punkapi.com/documentation/v2

 

Punk API: Brewdog's DIY Dog as an API

If you would like to contribute to keeping the lights on and the maintenance of Punk API, I'm accepting donations through these channels BTC ETH LTC

punkapi.com

 

 

해당 사이트에 들어가 API를 살펴보면 다음 주소를 통해 데이터를 얻을 수 있다고 소개되어 있다.

 

 

 

해당 주소창에 https://api.punkapi.com/v2/beers를 입력해보니 다음과 같이 원하는 beers 정보가 찍히는 것을 확인 할  수 있었다.

 

 

자 그럼 이제 해당 정보를 가져오고 저장할 struct를 만들자! 필자는 Beer라는 struct를 만들었다. 해당 데이터 전부를 사용할 필요는 없어서 id와 name, description, food_pairing만 가져오도록 작성했다.

import Foundation

struct Beer : Decodable {
    let id : Int?
    let name, description : String?
    let food_pairing : [String]?
}

 

 

자 그럼 이제 해당 데이터를 가져와 BeerList에 저장해주자!

 

 

 

 

 

DispatchQueue.main.async 와 관련된 내용은 해당 포스팅에서 참조할 수 있다.

2022.12.14 - [IOS] - [IOS / Swift] DispatchQueue.main

 

[IOS / Swift] DispatchQueue.main

URLSession을 사용하여 데이터를 받아와 ui에 편집할 때 DispatchQueue.main.async를 사용한 코드가 있어 검색을 하며 이해한 내용을 코드에 적고자 한다. 쓰레드(thread) 쓰레드(thread)란 프로세스(process) 내

hyukji.tistory.com