반응형
1...
//
// ViewController.swift
// newsApp
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableViewMain: UITableView!
//1. http 통신 방법
//2. json 데이터 형태
//api 키 : a8b568a8b61e437ba20914534af32f52
//뉴스 정보를 가져오는 http 함수 만들기
func getNews() {
let task = URLSession.shared.dataTask(with: URL(string: "https://newsapi.org/v2/top-headlines?country=kr&apiKey=a8b568a8b61e437ba20914534af32f52")!) { data, response, error in
//옵셔널 벗겨내기
if let datajson = data {
//json parsing
do {
let json = try JSONSerialization.jsonObject(with: datajson, options: [])
print(json)
}catch {
}
}
}
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//몇개? 숫자
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//무엇? 반복 10번?
//2번째 방법 재사용 셀, 친자확인 후 자식 데려오기
let cell = tableViewMain.dequeueReusableCell(withIdentifier: "type1", for: indexPath) as! type1
//as : as? as! = 친자확인
cell.typelabel.text = "\(indexPath.row)"
return cell
}
//클릭시 - 이벤트
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("\(indexPath.row)")
}
override func viewDidLoad() {
super.viewDidLoad()
//self : class viewcontroller 안의 func들을 의미함.
tableViewMain.delegate = self
tableViewMain.dataSource = self
getNews()
}
//tableview : 테이블로 된 뷰 - 여러개의 행이 모여있는 화면 목록
//1. 데이터 무엇?
//2. 데이터 몇개?
}
2...
//
// ViewController.swift
// newsApp
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var newsData: Array<Dictionary<String, Any>>?
@IBOutlet weak var tableViewMain: UITableView!
//1. http 통신 방법
//2. json 데이터 형태
//api 키 : a8b568a8b61e437ba20914534af32f52
//뉴스 정보를 가져오는 http 함수 만들기
func getNews() {
let task = URLSession.shared.dataTask(with: URL(string: "https://newsapi.org/v2/top-headlines?country=kr&apiKey=a8b568a8b61e437ba20914534af32f52")!) { data, response, error in
//옵셔널 벗겨내기
if let datajson = data {
//1.json parsing
do {
let json = try JSONSerialization.jsonObject(with: datajson, options: []) as! Dictionary<String, Any>
// print(json) // dictionary
//2.키값 가져오기
let article = json["articles"] as! Array<Dictionary<String, Any>>
//4.뉴스데이터 넣기
self.newsData = article
//6.메인에서 일하고, 데이터 뿌려주라고 통보
DispatchQueue.main.async {
self.tableViewMain.reloadData()
}
// print(article)
// 3. for 문으로 뽑아내기
// for(key,value) in article.enumerated() {
// if let v = value as? Dictionary<String,Any> {
// let title = v["title"]
// print(title)
// }
// }
//
}catch {
}
}
}
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//몇개? 숫자
//5. length
if let news = newsData {
return news.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//무엇? 반복 10번?
//2번째 방법 재사용 셀, 친자확인 후 자식 데려오기
let cell = tableViewMain.dequeueReusableCell(withIdentifier: "type1", for: indexPath) as! type1
//as : as? as! = 친자확인
let index = indexPath.row
if let news = newsData {
let row = news[index]
if let r = row as? Dictionary<String,Any> {
//optional 값 벗기기
if let title = r["title"] as? String {
cell.typelabel.text = title
}
}
}
return cell
}
//클릭시 - 이벤트
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("\(indexPath.row)")
}
override func viewDidLoad() {
super.viewDidLoad()
//self : class viewcontroller 안의 func들을 의미함.
tableViewMain.delegate = self
tableViewMain.dataSource = self
getNews()
}
//tableview : 테이블로 된 뷰 - 여러개의 행이 모여있는 화면 목록
//1. 데이터 무엇?
//2. 데이터 몇개?
}
1. 네트워크 통신을 위해서는 - urlsession
2. background : network / ui : main
from, 센치한 개발자
반응형
'개발언어 > Swift' 카테고리의 다른 글
스위프트 앱 로딩창 만들기 (0) | 2021.11.30 |
---|---|
스위프트 뉴스앱 만들기3 (table view) (0) | 2021.11.15 |
스위프트 뉴스앱 만들기1(2번째 방법 table view) (0) | 2021.10.14 |
스위프트 뉴스앱 만들기1(table view) (0) | 2021.10.13 |
스위프트(swift) unsplash 예제1 : view 만들기 (0) | 2021.09.25 |