개발 알다가도 모르겠네요

Json parsing 을 간단하게 알아보자. With 뉴스앱 본문

모바일/Swift

Json parsing 을 간단하게 알아보자. With 뉴스앱

이재빵 2021. 1. 31. 00:21
728x90

 

 

swift에서 data dictionary 타입입니다. (key, value)

 

func getNews() {
        let url = "https://newsapi.org/v2/top-headlines?country=kr&apiKey=248805a55af84f14b13e8e69456fb6dd"
       let task = URLSession.shared.dataTask(with: URL(string: url)!) { (data, response, error) in
            if let dataJson = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: dataJson, options: []) as! Dictionary<String, Any>   //swift에서 data는 dictionary 타입임 (key, value)
                
                    let articles = json["articles"] as! Array<Dictionary<String, Any>>
                    self.newsData = articles
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
                    
                } catch {
                    print(error)
                }
            }
        }
        task.resume()
        }