Skip to content

Commit

Permalink
Merge pull request #8 from DO-SOPT-iOS-Part/#7
Browse files Browse the repository at this point in the history
#7 리팩토링 과제
  • Loading branch information
kim-seonwoo authored Dec 21, 2023
2 parents aad0903 + 5147113 commit cdfd14d
Show file tree
Hide file tree
Showing 28 changed files with 620 additions and 337 deletions.
25 changes: 25 additions & 0 deletions assignment1/GenericResponse.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//
// GenericResponse.swift
// assignment1
//
// Created by Seonwoo Kim on 12/14/23.
//

import Foundation

struct GenericResponse<T: Codable>: Codable {
var code: Int
var message: String?
var data: T?

enum CodingKeys: String, CodingKey {
case code, message, data
}

init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
code = (try? values.decode(Int.self, forKey: .code)) ?? 0
message = (try? values.decode(String.self, forKey: .message)) ?? ""
data = (try? values.decode(T.self, forKey: .data)) ?? nil
}
}
76 changes: 76 additions & 0 deletions assignment1/MoyaLoggerPlugin.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//
// MoyaLoggerPlugin.swift
// assignment1
//
// Created by Seonwoo Kim on 12/14/23.
//

import Foundation
import Moya
import UIKit

final class MoyaLoggerPlugin: PluginType {
// Request를 보낼 때 호출
func willSend(_ request: RequestType, target: TargetType) {
guard let httpRequest = request.request else {
print("--> 유효하지 않은 요청")
return
}
let url = httpRequest.description
let method = httpRequest.httpMethod ?? "unknown method"
var log = "----------------------------------------------------\n[\(method)] \(url)\n----------------------------------------------------\n"
log.append("API: \(target)\n")
if let headers = httpRequest.allHTTPHeaderFields, !headers.isEmpty {
log.append("header: \(headers)\n")
}
if let body = httpRequest.httpBody, let bodyString = String(bytes: body, encoding: String.Encoding.utf8) {
log.append("\(bodyString)\n")
}
log.append("------------------- END \(method) --------------------------")
print(log)
}

// Response가 왔을 때
func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
switch result {
case let .success(response):
onSuceed(response, target: target, isFromError: false)
case let .failure(error):
onFail(error, target: target)
}
}

func onSuceed(_ response: Response, target: TargetType, isFromError: Bool) {
let request = response.request
let url = request?.url?.absoluteString ?? "nil"
let statusCode = response.statusCode

var log = "------------------- 네트워크 통신 성공(isFromError: \(isFromError)) -------------------"
log.append("\n[\(statusCode)] \(url)\n----------------------------------------------------\n")
log.append("API: \(target)\n")
response.response?.allHeaderFields.forEach {
log.append("\($0): \($1)\n")
}
if let reString = String(bytes: response.data, encoding: String.Encoding.utf8) {
log.append("\(reString)\n")
}
log.append("------------------- END HTTP (\(response.data.count)-byte body) -------------------")
print(log)
}

func onFail(_ error: MoyaError, target: TargetType) {
if let response = error.response {
onSuceed(response, target: target, isFromError: true)
return
}
var log = "네트워크 오류"
log.append("<-- \(error.errorCode) \(target)\n")
log.append("\(error.failureReason ?? error.errorDescription ?? "unknown error")\n")
log.append("<-- END HTTP")
print(log)

let alertViewController = UIAlertController(title: "네트워크 연결 실패", message: "네트워크 환경을 한번 더 확인해주세요.", preferredStyle: .alert)
alertViewController.addAction(UIAlertAction(title: "확인", style: .default, handler: nil))

}
}
15 changes: 15 additions & 0 deletions assignment1/NetworkResult.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// NetworkResult.swift
// assignment1
//
// Created by Seonwoo Kim on 12/14/23.
//
import Foundation

enum NetworkResult<T> {
case success(T) // 서버 통신 성공
case requestErr(T) // 요청 에러 발생
case pathErr // 경로 에러
case serverErr // 서버의 내부적 에러
case networkFail // 네트워크 연결 실패
}
15 changes: 15 additions & 0 deletions assignment1/URLConstant.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// URLConstant.swift
// assignment1
//
// Created by Seonwoo Kim on 12/14/23.
//

import Foundation

enum URLConstant {

// MARK: - Base URL
static let baseURL = "https://api.openweathermap.org/data/2.5"

}
5 changes: 0 additions & 5 deletions assignment1/assignment1/Applications/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else { return }

let window = UIWindow(windowScene: windowScene)
Expand Down Expand Up @@ -51,7 +48,5 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}


}

24 changes: 0 additions & 24 deletions assignment1/assignment1/Base.lproj/Main.storyboard

This file was deleted.

8 changes: 8 additions & 0 deletions assignment1/assignment1/Config.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>API_KEY</key>
<string>a9ed4b4ac1ed712e8e2b0e38959a23d1</string>
</dict>
</plist>
33 changes: 33 additions & 0 deletions assignment1/assignment1/Global/Extensions/String+.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//
// String+.swift
// assignment1
//
// Created by Seonwoo Kim on 12/11/23.
//

import Foundation

// 현재시간을 반환하기 위한 함수입니다.
func getCurrentTime() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"

let currentTime = Date()
let formattedTime = dateFormatter.string(from: currentTime)

return formattedTime
}

//시간 데이터를 포맷팅하는 함수
func extractHour(from dateString: String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

if let date = dateFormatter.date(from: dateString) {
let hourFormatter = DateFormatter()
hourFormatter.dateFormat = "HH"
return hourFormatter.string(from: date)
} else {
return nil
}
}
29 changes: 29 additions & 0 deletions assignment1/assignment1/Global/Extensions/UIColor+.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//
// UIColor+.swift
// assignment1
//
// Created by Seonwoo Kim on 12/9/23.
//

import UIKit

extension UIColor {

convenience init(hexCode: String, alpha: CGFloat = 1.0) {
var hexFormatted: String = hexCode.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

if hexFormatted.hasPrefix("#") {
hexFormatted = String(hexFormatted.dropFirst())
}

assert(hexFormatted.count == 6, "Invalid hex code used.")

var rgbValue: UInt64 = 0
Scanner(string: hexFormatted).scanHexInt64(&rgbValue)

self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: alpha)
}
}
25 changes: 25 additions & 0 deletions assignment1/assignment1/Global/Extensions/UIImage+.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//
// UIImage+.swift
// assignment1
//
// Created by Seonwoo Kim on 12/9/23.
//

import UIKit

extension UIImage {
func resized(withPercentage percentage: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage)
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
func resized(toWidth width: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
21 changes: 21 additions & 0 deletions assignment1/assignment1/Global/Extensions/UIStackView+.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//
// UIStackView+.swift
// assignment1
//
// Created by Seonwoo Kim on 12/9/23.
//

import UIKit

extension UIStackView {
func addArrangeSubViews(_ views: UIView...) {
views.forEach { self.addArrangedSubview($0) }
}

func clearSubViews() {
self.arrangedSubviews.forEach{
self.removeArrangedSubview($0) //superview에서 view 삭제
$0.removeFromSuperview() // 자식view에서도 superview 삭제
}
}
}
20 changes: 20 additions & 0 deletions assignment1/assignment1/Global/Extensions/UIView+.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//
// UIView+.swift
// assignment1
//
// Created by Seonwoo Kim on 12/9/23.
//
import UIKit

extension UIView {
func addSubviews(_ views: UIView...) {
views.forEach { self.addSubview($0) }
}

func setRoundBorder(borderColor: UIColor, borderWidth: CGFloat, cornerRadius: CGFloat) {
layer.masksToBounds = true
layer.borderColor = borderColor.cgColor
layer.borderWidth = borderWidth
layer.cornerRadius = cornerRadius
}
}
20 changes: 20 additions & 0 deletions assignment1/assignment1/Global/assignment1++Bundle.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//
// assignment1++Bundle.swift
// assignment1
//
// Created by Seonwoo Kim on 12/14/23.
//

import Foundation

extension Bundle {
var apikey: String {
guard let path = Bundle.main.path(forResource: "Config", ofType: "plist"),
let xml = FileManager.default.contents(atPath: path),
let config = try? PropertyListSerialization.propertyList(from: xml, options: .mutableContainers, format: nil) as? [String: Any],
let key = config["API_KEY"] as? String else {
fatalError("API_KEY not found in Config.plist")
}
return key
}
}
31 changes: 0 additions & 31 deletions assignment1/assignment1/Network/NetworkError.swift

This file was deleted.

Loading

0 comments on commit cdfd14d

Please sign in to comment.