[Swift] OpenAPI 활용 영화 순위 앱 만들기(1)

승민·2025년 5월 7일

Swift

목록 보기
8/10
post-thumbnail
  • OpenAPI 를 활용해서 영화진흥위원회에서 제공하는 영화 순위를 활용할 예정이에요.
  • Xcode 를 통해서 iOS 앱으로 만들어서 간편하게 정보를 확인할 수 있도록 해볼게요.

프로젝트 만들기

프로젝트 생성

이름 설정

Table View 추가

제약조건 추가

다음과 같이 변경

Assistant 띄운 후 Ctrl 드래그로 테이블 뷰 연결

연결 후 UITableViewDelegate, UITableViewDataSource 프로토콜 추가

기능 구현을 위한 코드 추가

실행 후 정상 동작여부 확인

section의 수를 2로 늘린 후 실행

실행결과 확인

TableView Cell 추가

Identifier를 myCell로 변경 후 적용

Cell 설정용 Cocoa Touch Calss 추가

부모 클래스를 UITableViewCell로 지정

생성한 Cell 선택 후 Class를 연결

셀 안에 Label 추가 후 제약조건을 추가

실행 결과 확인

Label 디자인

Assistant로 Label 선택 후 Ctrl 드래그

이름 지정 후 코드와 연결

코드를 다음과 같이 수정 후 실행

실행 결과 확인

소스 수정

실행결과 확인

indexPath를 통해 각 셀의 위치 확인

OpenAPI 결과 기반 영화 제목 확인

5위까지 영화 제목을 가져와서 테스트용으로 실행

실행결과 확인

tableView(_:didSelectRowAt:)를 통한 특정 셀 선택 이벤트 확인

tableView(_:cellForRowAt:)를 통해서 현재 출력되는 셀 확인

네트워크 연결하기

  • URL 만들기
    • URL(string: String)
  • URLSession 만들기
    • URLSession(configuration: URLSessionConfiguration)
  • URLSession 인스턴스에게 task주기
    • URLSession인스턴스.dataTask(with:completionHandler:)
  • task시작하기
    • URLSessionTask인스턴스.resume()

URL 만들기

URLSession 만들기

URLSession 인스턴스에게 task주기

task 시작하기

String으로 변환 후 내용 출력하기

전체 코드

import UIKit

let movie=["야당", "A MINECRAFT MOVIE 마인크래프트 무비","썬더볼츠*", "거룩한 밤: 데몬 헌터스", "파과"]
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var table: UITableView!
    let movieURL = "https://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=<API Key>&targetDt=20250506"
    override func viewDidLoad() {
        super.viewDidLoad()
        table.delegate = self
        table.dataSource = self
        getData()
    }
    func getData() {
        // 함수 안에서는 guard-let 으로 Optional unWrapping하는 것이 가독성이 좋음
        guard let url = URL(string: movieURL) else { return }
        let session = URLSession(configuration: .default)
        // session.dataTask는 선언할 함수의 내용이 길기 때문에 후행 클로저로 처리
        let task = session.dataTask(with: url) { data, response, error in
            if error != nil {
                print(error!)
                return
            }
            guard let JSONdata = data else { return }
            // print(JSONdata)
            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]
        // print(indexPath.description)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //print(indexPath.description) // 개발자용 print 구문
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
}

정리

  • OpenAPI 를 활용해서 영화진흥위원회에서 제공하는 영화 순위를 받아왔어요.
  • Xcode 를 통해서 iOS 앱으로 만들어서 가져오는 부분까지 구현했어요.

출처 : Smile Han - iOS 프로그래밍 기초

0개의 댓글