iOS/iOS SeSAC 2기 TIL

iOS swift 맥주 추천 앱 만들기

Developer-Michelle 2022. 8. 1. 20:38

맥주 추천 앱 만들기

 

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

 

page=5 & per_page = 80으로 했을때가 마지막 페이지인 것을 알 수 있었다.

따라서 마지막 맥주의 id는 325 라는 것을 알 수 있었다.

 

let url = "https://api.punkapi.com/v2/beers/\(number)"

 

버튼 클릭시마다 숫자를 랜덤으로 생성해서 url 마지막 number에 넣어줄 수 있었다.

 @IBAction func buttonClicked(_ sender: UIButton) {

       requestBeer(number: Int.random(in: 1...325))

    }

 

오늘 알게된 것:

 

1. json 페이지가 어떤 형태로 되어있는가를 잘 살펴야 함.

 

아래처럼 배열 안에 여러개가 놓인 경우, 배열에서 하나를 가져오는 형태로 원하는 name, image_url, description 등을 추출해야 함.

 

 

원래 SwiftyJSON github page에서 제공하는 소스는 다음과 같다.

let json = JSON(value)

print("JSON: \(json)")

 

위에처럼 가져오면 안되고, 배열이기 때문에 아래처럼 가져왔어야 했다.

print("JSONArray: \(json.array![0]["name"].stringValue)")

json.array![0]은 위의 페이지에서 [ ] 를 제거하고 알멩이를 가져오게 되고,

여기에 json.array![0]["name"] 까지 붙여주면 name요소를 가져오는 것.

 

 

 

2. json 형태의 imageURL을 가져올 때 아래와 같이 해야 했다.

 

 

*image가 한번 hidden되면 쭉 hidden 되기 때문에 if, else 로 나누어 토글처럼 구현해야 했음.