Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Week4 기본과제 #14

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 88 additions & 16 deletions Sopt_Seminar/Sopt_Seminar.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
"version" : "1.2.3"
}
},
{
"identity" : "kingfisher",
"kind" : "remoteSourceControl",
"location" : "https://github.com/onevcat/Kingfisher.git",
"state" : {
"revision" : "af4be924ad984cf4d16f4ae4df424e79a443d435",
"version" : "7.6.2"
}
},
{
"identity" : "snapkit",
"kind" : "remoteSourceControl",
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,4 @@
uuid = "03F0E121-6951-4635-A1D8-E0CE9AD0D4C7"
type = "1"
version = "2.0">
<Breakpoints>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
uuid = "FDBF13C5-92B8-47B6-B37B-B66ABA2F638E"
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "Sopt_Seminar/Week4/NetworkResult&lt;T&gt;.swift"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "24"
endingLineNumber = "24"
landmarkName = "SignUpResponse"
landmarkType = "14">
</BreakpointContent>
</BreakpointProxy>
</Breakpoints>
</Bucket>
6 changes: 6 additions & 0 deletions Sopt_Seminar/Sopt_Seminar/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,17 @@
<string>$(API_Key)</string>
<key>BASE_URL</key>
<string>$(BASE_URL)</string>
<key>MovieAPI_Key</key>
<string>$(MovieAPI_Key)</string>
<key>Movie_URL</key>
<string>$(Movie_URL)</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>Poster_URL</key>
<string>$(Poster_URL)</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
Expand Down
61 changes: 61 additions & 0 deletions Sopt_Seminar/Sopt_Seminar/Week3/Assignment/Model/MovieModel.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//
// MovieModel.swift
// Sopt_Seminar
//
// Created by 김응관 on 2023/05/12.
//

import Foundation

// MARK: - Welcome
struct Welcome: Codable {
let page: Int
let results: [Result]
let totalPages, totalResults: Int

enum CodingKeys: String, CodingKey {
case page, results
case totalPages = "total_pages"
case totalResults = "total_results"
}
}

// MARK: - Result
struct Result: Codable {
let adult: Bool
let backdropPath: String
let genreIDS: [Int]
let id: Int
let originalLanguage: OriginalLanguage
let originalTitle, overview: String
let popularity: Double
let posterPath, releaseDate, title: String
let video: Bool
let voteAverage: Double
let voteCount: Int

enum CodingKeys: String, CodingKey {
case adult
case backdropPath = "backdrop_path"
case genreIDS = "genre_ids"
case id
case originalLanguage = "original_language"
case originalTitle = "original_title"
case overview, popularity
case posterPath = "poster_path"
case releaseDate = "release_date"
case title, video
case voteAverage = "vote_average"
case voteCount = "vote_count"
}
}

enum OriginalLanguage: String, Codable {
case en = "en"
case fr = "fr"
}

// 영화 포스터 객체를 생성하기 위한 구조체
struct Movie {
let url: String
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//
// MovieConfig.swift
// Sopt_Seminar
//
// Created by 김응관 on 2023/05/12.
//

import Foundation

enum MovieConfig {

enum Keys {
enum Plist {
static let movieURL = "Movie_URL"
static let API_Key = "MovieAPI_Key"
static let imgURL = "Poster_URL"
}
}

private static let infoDictionary: [String: Any] = {
guard let dict = Bundle.main.infoDictionary
else {
fatalError("plist cannot found.")
}
return dict
}()
}

extension MovieConfig {
static let movieURL: String = {
guard let key = MovieConfig.infoDictionary[Keys.Plist.movieURL] as? String else {
fatalError("Base URL is not set in plist for this configuration.")
}
return key
}()

static let API_Key: String = {
guard let API_Key = MovieConfig.infoDictionary[Keys.Plist.API_Key] as? String else {
fatalError("Base URL is not set in plist for this configuration.")
}
return API_Key
}()

static let imgURL: String = {
guard let API_Key = MovieConfig.infoDictionary[Keys.Plist.imgURL] as? String else {
fatalError("Base URL is not set in plist for this configuration.")
}
return API_Key
}()

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
//
// MovieViewController.swift
// Sopt_Seminar
//
// Created by 김응관 on 2023/05/12.
//

import UIKit
import SnapKit

class MoviePosterViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
getMovie()
// Do any additional setup after loading the view.
}

private func getMovie() {
MovieService.shared.getInfo(key: "75df104409445c36a314b12eb0aa5fdb", language: "ko", adult: false, video: false, page: 1) { response in

switch response {
case .success(let data):
guard let data = data as? Welcome else { return }
dump(data)
default:
return
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
//
// MovieService.swift
// Sopt_Seminar
//
// Created by 김응관 on 2023/05/12.
//



import Alamofire
import Foundation

final class MovieService {

static let shared = MovieService()

private init() {}

func getInfo(key: String, language: String, adult: Bool, video: Bool, page: Int, completion: @escaping (NetworkState<Any>) -> Void) {

let header: HTTPHeaders = [
"Content-Type": "application/json",
]

let url = MovieConfig.movieURL + "api_key=\(key)&include_adult=\(adult)&include_video=\(video)&language=\(language)&page=\(page)&sort_by=popularity.desc"

let dataRequest = AF.request(url, method: .get, headers: header)

dataRequest.responseData { response in

switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else { return }
guard let value = response.value else { return }

let networkResult = self.judgeStatus(by: statusCode, value)
completion(networkResult)
case .failure:
completion(.networkErr)
}
}
}

private func judgeStatus(by statusCode: Int, _ data: Data) -> NetworkState<Any> {
switch statusCode {
case 200: return isValidData(data: data)
case 201: return isValidData(data: data)
case 400, 409: return isValidData(data: data)
case 500: return .serverErr
default: return .networkErr
}
}

private func isValidData(data: Data) -> NetworkState<Any> {
let decoder = JSONDecoder()

guard let decodedData = try? decoder.decode(Welcome.self, from: data)
else { return .pathErr }

return .success(decodedData as Any)
}
}
21 changes: 21 additions & 0 deletions Sopt_Seminar/Sopt_Seminar/Week3/Assignment/Protocols/Enums.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//
// UserInfo.swift
// Sopt_Seminar
//
// Created by 김응관 on 2023/05/08.
//

import Foundation

enum LoginState: String {
case logIn
case logOut
}

enum NetworkState<T> {
case success(T) // 서버 통신 성공
case requestErr(T) // 요청에러 발생
case pathErr // 경로 에러
case serverErr // 서버 내부 에러
case networkErr // 네트워크 연결 실패
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import UIKit
import SnapKit
import Kingfisher

class MovieCollectionViewCell: UICollectionViewCell {

Expand Down Expand Up @@ -41,8 +42,8 @@ class MovieCollectionViewCell: UICollectionViewCell {
}
}

// 5. 이미지 설정
// 5. 이미지 설정 -> URL객체를 만든 후 KingFisher의 setImage 메서드를 통해 영화포스터 띄워준다
func setImage(_ name: String) {
poster.image = UIImage(named: name)?.resized(withPercentage: 3.0)
poster.kf.setImage(with: URL(string: name))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ import UIKit

class MovieTableViewCell: UITableViewCell {

// Poster 이미지 목록
private var items: [String] = ["movie1", "movie2", "movie3", "movie1", "movie2"]
// 현재 뷰에서 보이는 CollectionView상의 이미지 데이터 계속 reload
var datas: [Movie] = [] {
didSet {
self.collectionView.reloadData()
}
}

// init
@available(*, unavailable)
Expand Down Expand Up @@ -109,15 +113,14 @@ extension MovieTableViewCell: UICollectionViewDataSource, UICollectionViewDelega

// CollectionView 개수
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
self.items.count
self.datas.count
}

// 반환 cell 설정
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MovieCollectionViewCell.className, for: indexPath) as! MovieCollectionViewCell

cell.setImage(items[indexPath.row])
cell.setImage(datas[indexPath.row].url)
return cell
}
}
Expand Down
Loading