원하는 상황 json 을 받아오는 동안 indicator 도 뜨고, 타이머도 멈추지 않도록 GCD 적절히 섞으면서 사용하는 방식으로 진행
기존 코드
@IBAction func onLoad() {
editView.text = ""
setVisibleWithAnimation(activityIndicator, true)
let url = URL(string: MEMBER_LIST_URL)!
let data = try! Data(contentsOf: url)
let json = String(data: data, encoding: .utf8)
self.editView.text = json
self.setVisibleWithAnimation(self.activityIndicator, false)
}
바뀐 코드
func downloadJson(_ url: String, _ completion: @escaping (String?) -> Void) {
DispatchQueue.global().async {
let url = URL(string: url)!
let data = try! Data(contentsOf: url)
let json = String(data: data, encoding: .utf8)
DispatchQueue.main.async {
completion(json)
}
}
// 데이터와 UI 가 asynchrounous 하게 변동되도록
}
@IBAction func onLoad() {
editView.text = ""
setVisibleWithAnimation(activityIndicator, true)
downloadJson(MEMBER_LIST_URL) { json in
self.editView.text = json
self.setVisibleWithAnimation(self.activityIndicator, false)
}
// completion handler 전달
}
하지만 위 방법은,