iOS 프로그래밍 실무 10주차
TableView Constraints 이용해 가득 채우기
프로토콜 채택 Fix
Table View Cell Constaints(margin 5)
네트워킹
- URL 만들기
- URL(string: String)
- URLSession 만들기
- URLSession(configuration: URLSessionConfiguration)
- URLSesstion 인스턴스에게 task 주기
- URLSession인스턴스.dataTask(with:completionHandler:)
- tsak 시작하기
- URLSessionTask인스턴스.resume()
https://developer.apple.com/documentation/foundation/url
URL | Apple Developer Documentation
A value that identifies the location of a resource, such as an item on a remote server or the path to a local file.
developer.apple.com
함수 안 옵셔널 풀기
if - let
func getData() {
if let url = URL(string: movieURL) {
print(url)
}
}
guard - let
func getData() {
guard let url = URL(string: movieURL) else {
return
}
print(url)
}
언래핑 된 url 변수를 guard 문 밖에 있는 코드가 사용 가능함
https://developer.apple.com/documentation/foundation/urlsession
URLSession | Apple Developer Documentation
An object that coordinates a group of related, network data transfer tasks.
developer.apple.com
func getData() {
guard let url = URL(string: movieURL) else {
return
}
let session = URLSession(configuration: .default)
session.dataTask(with: url, completionHandler: <#T##(Data?, URLResponse?, (any Error)?) -> Void#>)
}
<#T##(Data?, URLResponse?, (any Error)?) -> Void#> 이부분 Enter 누르면
func getData() {
guard let url = URL(string: movieURL) else {
return
}
let session = URLSession(configuration: .default)
session.dataTask(with: url) { <#Data?#>, <#URLResponse?#>, <#(any Error)?#> in
<#code#>
}
}
자동으로 후행 클로저로 만들어줌
let movieURL = "https://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=fecd5be7de01c30e13107d1967fe285d&targetDt=20250506"
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
getData()
}
func getData() {
guard let url = URL(string: movieURL) else {
return
}
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { data, response, error in
if error != nil { // 없어도 됨, error 처리
print(error!)
return
}
guard let JSONdata = data else {
return
}
let dataString = String(data:JSONdata, encoding: .utf8)
print(dataString!)
}
task.resume()
}
콘솔 창
ViewController.swfit
import UIKit
let movie = ["야당1", "A MINECRAFT MOVIE 마인크래프트 무비1", "썬더볼츠*1", "거룩한 밤: 데몬 헌터스1", "파과1"]
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var table: UITableView!
let movieURL = "https://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=fecd5be7de01c30e13107d1967fe285d&targetDt=20150506"
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
getData()
}
func getData() {
guard let url = URL(string: movieURL) else {
return
}
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { data, response, error in
if error != nil { // 없어도 됨, error 처리
print(error!)
return
}
guard let JSONdata = data else {
return
}
let dataString = String(data:JSONdata, encoding: .utf8)
print(dataString!)
}
task.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyTableViewCell
cell.movieName.text = movie[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//print(indexPath.description)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
}
MyTableViewCell.swift
import UIKit
class MyTableViewCell: UITableViewCell {
@IBOutlet weak var movieName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
Instantly parse JSON in any language | quicktype
app.quicktype.io
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let welcome = try? JSONDecoder().decode(Welcome.self, from: jsonData)
import Foundation
// MARK: - Welcome
struct Welcome {
let boxOfficeResult: BoxOfficeResult
}
// MARK: - BoxOfficeResult
struct BoxOfficeResult {
let boxofficeType, showRange: String
let dailyBoxOfficeList: [DailyBoxOfficeList]
}
// MARK: - DailyBoxOfficeList
struct DailyBoxOfficeList {
let rnum, rank, rankInten: String
let rankOldAndNew: RankOldAndNew
let movieCD, movieNm, openDt, salesAmt: String
let salesShare, salesInten, salesChange, salesAcc: String
let audiCnt, audiInten, audiChange, audiAcc: String
let scrnCnt, showCnt: String
}
enum RankOldAndNew: String {
case old
}
ChatGPT
import Foundation
struct MovieData: Codable {
let boxOfficeResult: BoxOfficeResult
}
struct BoxOfficeResult: Codable {
let boxofficeType: String
let showRange: String
let dailyBoxOfficeList: [DailyBoxOffice]
}
struct DailyBoxOffice: Codable {
let rnum: String
let rank: String
let rankInten: String
let rankOldAndNew: String
let movieCd: String
let movieNm: String
let openDt: String
let salesAmt: String
let salesShare: String
let salesInten: String
let salesChange: String
let salesAcc: String
let audiCnt: String
let audiInten: String
let audiChange: String
let audiAcc: String
let scrnCnt: String
let showCnt: String
}
perplexity
struct MovieData: Codable {
let rank: String
let movieCode: String
let movieName: String
let openDate: String
let salesAmount: String
let salesShare: String
let salesAccumulated: String
let audienceCount: String
let audienceAccumulated: String
let screenCount: String
let showCount: String
}
출처: iOS 프로그래밍 실무 강의 자료