본문 바로가기
Project/NETFLIX

NETFLIX CLONE 6편 (String 기능 확장, 섹션별 함수 생성)

by 밤새는탐험가 2024. 5. 8.

 

✅ Extensions를 통해 String 타입 기능 확장

✅ 각 섹션별 함수 생성

 


✅ Extensions를 통해 String 타입 기능 확장

  • Resource 폴더 내에 Extensions 파일 생성 
  • String 타입의 데이터를 첫 번째는 대문자, 나머지는 소문자로 설정되게 코드 구현 
import Foundation


extension String {
    
    func capitalizeFirstLetters() -> String {
        return self.prefix(1).uppercased() + self.lowercased().dropFirst()
    }
}

 

 

  • 홈뷰컨트롤러의 extension 부분에 위에 정의한 함수를 호출 
// 각 셀의 머리말 폰트 적용
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let header = view as? UITableViewHeaderFooterView else { return }

    header.textLabel?.font = .systemFont(ofSize: 18, weight: .semibold)
    header.textLabel?.frame = CGRect(x: header.bounds.origin.x + 20, y: header.bounds.origin.y, width: 100, height: header.bounds.height)
    header.textLabel?.textColor = .label
    header.textLabel?.text = header.textLabel?.text!.capitalizeFirstLetters()

}

 

 

 

 

✅ 각 섹션별 함수 생성

  • "Trending Movies", "Trending Tv", "Popular", "Upcoming Movies", "Top rated" 함수 생성
// Trending tv 불러올 함수
    func getTrendingTvs(completion: @escaping (Result<[String], Error>) -> Void) {
        
        guard let url = URL(string: "\(Constants.baseURL)3/trending/tv/day?api_key=\(Constants.API_KEY)") else { return }
        
        let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
            guard let data = data, error == nil else { return }
            
            do {
                let results = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)
                print(results)
            } catch {
                print(error.localizedDescription)
            }
        }
        
        task.resume()
    }

 

  • getTrendingTvs 함수 호출로 갖고 온 데이터를 토대로 Tv라는 데이터 모델 생성 
import Foundation


struct TrendingTvResponse: Codable {
    let results: [Tv]
}

struct Tv: Codable {
    let id: Int
    let media_type: String?
    let original_name: String?
    let original_title: String?
    let poster_path: String?
    let overview: String?
    let vote_count: Int
    let release_date: String?
    let vote_average: Double
}

 

 

  • 위에 생성한 Tv라는 데이터 모델을 getTrendingTvs 함수에 적용
 func getTrendingTvs(completion: @escaping (Result<[Tv], Error>) -> Void) {
        
        guard let url = URL(string: "\(Constants.baseURL)3/trending/tv/day?api_key=\(Constants.API_KEY)") else { return }
        
        let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
            guard let data = data, error == nil else { return }
            
            do {
                let results = try JSONDecoder().decode(TrendingTvResponse.self, from: data)
                print(results)
            } catch {
                print(error.localizedDescription)
            }
        }
        
        task.resume()
    }

 

 

  • 그 외에 섹션별 함수를 생성
    // upcoming Movie 불러올 함수
    func getUpcomingMovies(completion: @escaping (Result<[Movie], Error>) -> Void) {
        guard let url = URL(string: "\(Constants.baseURL)/3/movie/upcoming?api_key=\(Constants.API_KEY)&language=en-US&page=1") else { return }
        
        let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
            guard let data = data, error == nil else { return }
            
            do {
                let results = try JSONDecoder().decode(TrendingMoviesResponse.self, from: data)
                print(results)
            } catch {
                print(error.localizedDescription)
            }
        }
        
        task.resume()
    }
    
    
    // popular 불러올 함수  
    func getPopular(completion: @escaping (Result<[Movie], Error>) -> Void) {
        guard let url = URL(string: "\(Constants.baseURL)/3/movie/popular?api_key=\(Constants.API_KEY)&language=en-US&page=1") else { return }
        
        let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
            guard let data = data, error == nil else { return }
            
            do {
                let results = try JSONDecoder().decode(TrendingMoviesResponse.self, from: data)
                print(results)
            } catch {
                print(error.localizedDescription)
            }
        }
        task.resume()
    }
    
    
  	// Top Rated gkatn
    func getTopRated(completion: @escaping (Result<[Movie], Error>) -> Void) {
        guard let url = URL(string: "\(Constants.baseURL)/3/movie/top_rated?api_key=\(Constants.API_KEY)&language=en-US&page=1") else { return }
        
        let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
            guard let data = data, error == nil else { return }
            
            do {
                let results = try JSONDecoder().decode(TrendingMoviesResponse.self, from: data)
                print(results)
            } catch {
                print(error.localizedDescription)
            }
        }
        task.resume()
    }

 

 

https://youtu.be/9InccoI9kQA?si=NxL4RZWWDHd7oTog