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

[Jed] Step1 - 로그인 화면 구현, 네트워크 통신 구현 관련 리팩토링 #16

Open
wants to merge 12 commits into
base: jed
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
24 changes: 20 additions & 4 deletions SignUp/SignUp.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@
B557E9C627F4401700448EC6 /* LoginViewDeleagte.swift in Sources */ = {isa = PBXBuildFile; fileRef = B557E9C527F4401700448EC6 /* LoginViewDeleagte.swift */; };
B557E9C827F441D200448EC6 /* HttpRequestHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = B557E9C727F441D200448EC6 /* HttpRequestHandler.swift */; };
B557E9CC27F4776A00448EC6 /* LoginUserProcotol.swift in Sources */ = {isa = PBXBuildFile; fileRef = B557E9CB27F4776A00448EC6 /* LoginUserProcotol.swift */; };
B557E9CE27F48A1E00448EC6 /* AlertPresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B557E9CD27F48A1E00448EC6 /* AlertPresentable.swift */; };
B557E9DE27F58D8500448EC6 /* AlertPresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B557E9DD27F58D8500448EC6 /* AlertPresentable.swift */; };
B557E9E027F5966400448EC6 /* HttpResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = B557E9DF27F5966400448EC6 /* HttpResponse.swift */; };
B571ECD527F354E400DF501F /* LoginViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B571ECD427F354E400DF501F /* LoginViewController.swift */; };
B571ECD827F355C300DF501F /* LoginView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B571ECD727F355C300DF501F /* LoginView.swift */; };
B571ECDA27F363BE00DF501F /* SigningUpView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B571ECD927F363BE00DF501F /* SigningUpView.swift */; };
B571ECDC27F3722900DF501F /* PersonalInfoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B571ECDB27F3722900DF501F /* PersonalInfoViewController.swift */; };
B571ECDE27F3723C00DF501F /* PersonalInfoView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B571ECDD27F3723C00DF501F /* PersonalInfoView.swift */; };
B5EC66A427F74A010042EFCF /* HttpResponseHandleable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5EC66A327F74A010042EFCF /* HttpResponseHandleable.swift */; };
B5F8730727F19EE700FFFE7F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5F8730627F19EE700FFFE7F /* AppDelegate.swift */; };
B5F8730927F19EE700FFFE7F /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5F8730827F19EE700FFFE7F /* SceneDelegate.swift */; };
B5F8730B27F19EE700FFFE7F /* SigningUpViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B5F8730A27F19EE700FFFE7F /* SigningUpViewController.swift */; };
Expand All @@ -30,12 +32,14 @@
B557E9C527F4401700448EC6 /* LoginViewDeleagte.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginViewDeleagte.swift; sourceTree = "<group>"; };
B557E9C727F441D200448EC6 /* HttpRequestHandler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HttpRequestHandler.swift; sourceTree = "<group>"; };
B557E9CB27F4776A00448EC6 /* LoginUserProcotol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginUserProcotol.swift; sourceTree = "<group>"; };
B557E9CD27F48A1E00448EC6 /* AlertPresentable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AlertPresentable.swift; sourceTree = "<group>"; };
B557E9DD27F58D8500448EC6 /* AlertPresentable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = AlertPresentable.swift; path = SignUp/Controllers/Protocols/AlertPresentable.swift; sourceTree = SOURCE_ROOT; };
B557E9DF27F5966400448EC6 /* HttpResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HttpResponse.swift; sourceTree = "<group>"; };
B571ECD427F354E400DF501F /* LoginViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginViewController.swift; sourceTree = "<group>"; };
B571ECD727F355C300DF501F /* LoginView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginView.swift; sourceTree = "<group>"; };
B571ECD927F363BE00DF501F /* SigningUpView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SigningUpView.swift; sourceTree = "<group>"; };
B571ECDB27F3722900DF501F /* PersonalInfoViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersonalInfoViewController.swift; sourceTree = "<group>"; };
B571ECDD27F3723C00DF501F /* PersonalInfoView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersonalInfoView.swift; sourceTree = "<group>"; };
B5EC66A327F74A010042EFCF /* HttpResponseHandleable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = HttpResponseHandleable.swift; path = SignUp/Controllers/Protocols/HttpResponseHandleable.swift; sourceTree = SOURCE_ROOT; };
B5F8730327F19EE700FFFE7F /* SignUp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SignUp.app; sourceTree = BUILT_PRODUCTS_DIR; };
B5F8730627F19EE700FFFE7F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
B5F8730827F19EE700FFFE7F /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -70,7 +74,6 @@
isa = PBXGroup;
children = (
B557E9C527F4401700448EC6 /* LoginViewDeleagte.swift */,
B557E9CD27F48A1E00448EC6 /* AlertPresentable.swift */,
);
path = DelegateProtocols;
sourceTree = "<group>";
Expand All @@ -79,6 +82,7 @@
isa = PBXGroup;
children = (
B557E9C727F441D200448EC6 /* HttpRequestHandler.swift */,
B557E9DF27F5966400448EC6 /* HttpResponse.swift */,
);
path = Common;
sourceTree = "<group>";
Expand All @@ -94,6 +98,7 @@
B571ECD327F1FA1100DF501F /* Controllers */ = {
isa = PBXGroup;
children = (
B5EC66A527F754CE0042EFCF /* Protocols */,
B5F8730A27F19EE700FFFE7F /* SigningUpViewController.swift */,
B571ECD427F354E400DF501F /* LoginViewController.swift */,
B571ECDB27F3722900DF501F /* PersonalInfoViewController.swift */,
Expand All @@ -112,6 +117,15 @@
path = Views;
sourceTree = "<group>";
};
B5EC66A527F754CE0042EFCF /* Protocols */ = {
isa = PBXGroup;
children = (
B557E9DD27F58D8500448EC6 /* AlertPresentable.swift */,
B5EC66A327F74A010042EFCF /* HttpResponseHandleable.swift */,
);
path = Protocols;
sourceTree = "<group>";
};
B5F872FA27F19EE700FFFE7F = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -216,18 +230,20 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
B557E9DE27F58D8500448EC6 /* AlertPresentable.swift in Sources */,
B557E9CC27F4776A00448EC6 /* LoginUserProcotol.swift in Sources */,
B571ECD527F354E400DF501F /* LoginViewController.swift in Sources */,
B571ECDA27F363BE00DF501F /* SigningUpView.swift in Sources */,
B5F8730B27F19EE700FFFE7F /* SigningUpViewController.swift in Sources */,
B557E9CE27F48A1E00448EC6 /* AlertPresentable.swift in Sources */,
B557E9C827F441D200448EC6 /* HttpRequestHandler.swift in Sources */,
B557E9C627F4401700448EC6 /* LoginViewDeleagte.swift in Sources */,
B557E9C327F43B8800448EC6 /* LoginUser.swift in Sources */,
B5F8730727F19EE700FFFE7F /* AppDelegate.swift in Sources */,
B571ECDE27F3723C00DF501F /* PersonalInfoView.swift in Sources */,
B571ECDC27F3722900DF501F /* PersonalInfoViewController.swift in Sources */,
B5EC66A427F74A010042EFCF /* HttpResponseHandleable.swift in Sources */,
B571ECD827F355C300DF501F /* LoginView.swift in Sources */,
B557E9E027F5966400448EC6 /* HttpResponse.swift in Sources */,
B5F8730927F19EE700FFFE7F /* SceneDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down
77 changes: 53 additions & 24 deletions SignUp/SignUp/Common/HttpRequestHandler.swift
Original file line number Diff line number Diff line change
@@ -1,48 +1,77 @@
import Foundation
import OSLog

enum HttpMethod: String{
case get = "GET"
case post = "POST"
case put = "PUT"
}

enum HttpResponseKey: String{
case responseBodyData = "responseBodyData"
enum HttpMethod: CustomStringConvertible{
case get
case post
case put

var description: String{
switch self{
case .get:
return "GET"
case .post:
return "POST"
case .put:
return "PUT"
}
}
}

struct NotificationName{
static let normalResponseReceived = Notification.Name("normalResponseReceived")
enum HttpError: Error, CustomStringConvertible{
case normalError(error: Error)
case dataNotReceivedError
case requestError

var description: String{
switch self {
case .normalError(let error):
return error.localizedDescription
case .dataNotReceivedError:
return "data not received"
case .requestError:
return "client request error"
}
}
}

class HttpRequestHandler{

static let logger = Logger()
static func sendRequest(data: Data?, url: URL, httpMethod: HttpMethod, completion: @escaping ()->Void){
static func generateURLRequest(data: Data?, url: URL, httpMethod: HttpMethod) -> URLRequest{
var request = URLRequest(url: url)
request.httpMethod = httpMethod.rawValue
request.httpMethod = "\(httpMethod)"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = data
return request
}

static func sendRequest(data: Data?, url: URL, httpMethod: HttpMethod, target: HttpResponseHandlable) {
let request = generateURLRequest(data: data, url: url, httpMethod: httpMethod)
URLSession.shared.dataTask(with: request){ data, response, error in
guard error == nil else {
self.logger.error("\(error.debugDescription)")
if let error = error{
self.handleResponse(target: target, result: .failure(HttpError.normalError(error: error)))
return
}

guard let data = data, let response = response as? HTTPURLResponse else {
self.logger.error("Could not receive any response or data")
//네트워크 오류로 인한 로그인 실패 출력
self.handleResponse(target: target, result: .failure(HttpError.dataNotReceivedError))
return
}

if(response.statusCode >= 400){
self.logger.debug("detected response with \(response.statusCode) status\nurl : \(url)")
self.handleResponse(target: target, result: .failure(HttpError.requestError))
return
}

guard let responseBody = try? JSONDecoder().decode(Dictionary<String, String>.self, from: data) else { return }
NotificationCenter.default.post(name: NotificationName.normalResponseReceived, object: self, userInfo: [HttpResponseKey.responseBodyData:responseBody])

self.handleResponse(target: target, result: .success(data))
}.resume()
}

static func handleResponse(target: HttpResponseHandlable, result: Result<Data, Error>){
switch result{
case .success(let data):
target.handleSuccess(data: data)
case .failure(let error):
target.handleFailure(error: error)
}
}
}
12 changes: 12 additions & 0 deletions SignUp/SignUp/Common/HttpResponse.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import Foundation

struct HttpResponse: Codable{

var result: String?
var status: String?

init(result: String, status: String){
self.result = result
self.status = status
}
}
35 changes: 28 additions & 7 deletions SignUp/SignUp/Controllers/LoginViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,45 @@ class LoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
loginView.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(responseReceived(_:)), name: NotificationName.normalResponseReceived, object: HttpRequestHandler.self)
}
}

extension LoginViewController: LoginViewDelegate{
extension LoginViewController: LoginViewDelegate, HttpResponseHandlable{

func determiningLoginButtonValidationRequested(id: String, password: String) {
if(isInputValid(id: id, password: password)){
self.loginView.validateLoginButton()
}else{
self.loginView.invalidateLoginButton()
}

func isInputValid(id: String, password: String)-> Bool{
if(id.count <= 0 || password.count <= 0){
return false
}
return true
}
}

func sendIdAndPasswordInput(id: String, password: String) {
let loginUser = LoginUser(id: id, password: password)
let jsonData = try? JSONEncoder().encode(loginUser)
if let url = URL(string: "https://api.codesquad.kr/signup"){
HttpRequestHandler.sendRequest(data: jsonData, url: url, httpMethod: HttpMethod.post){}
HttpRequestHandler.sendRequest(data: jsonData, url: url, httpMethod: HttpMethod.post, target: self)
}
}

@objc func responseReceived(_ notification: Notification){
guard let responseBody = notification.userInfo?[HttpResponseKey.responseBodyData] as? Dictionary<String,String> else { return }
guard let status = responseBody["status"] else { return }

func handleSuccess(data: Data) {
guard let responseBody = try? JSONDecoder().decode(HttpResponse.self, from: data) else { return }
self.composeAlertWithResponse(responseBody: responseBody)
}

func handleFailure(error: Error) {
self.presentAlert(title: "네트워크 에러", message: "\(error)")
}

func composeAlertWithResponse(responseBody: HttpResponse){
guard let status = responseBody.status else { return }
var alertMessage: String = ""
if(status == "409"){
alertMessage = "로그인 성공"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import Foundation

protocol HttpResponseHandlable{
func handleSuccess(data: Data)
func handleFailure(error: Error)
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ import Foundation

protocol LoginViewDelegate: AnyObject{
func sendIdAndPasswordInput(id: String, password: String)
func determiningLoginButtonValidationRequested(id: String, password: String)
}
32 changes: 10 additions & 22 deletions SignUp/SignUp/Views/LoginView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class LoginView: UIView {
@IBOutlet weak var idTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
var delegate: LoginViewDelegate?
weak var delegate: LoginViewDelegate?

@IBAction func loginButtonTouched(_ sender: UIButton) {
guard let idInput = self.idTextField.text else { return }
Expand All @@ -14,40 +14,28 @@ class LoginView: UIView {
}

@IBAction func idInputEditingChanged(_ sender: UITextField) {
self.checkLoginButtonValidation()
guard let idInput = self.idTextField.text else { return }
guard let passwordInput = self.passwordTextField.text else { return }
self.delegate?.determiningLoginButtonValidationRequested(id: idInput, password: passwordInput)
}

@IBAction func passwordInputEditingChanged(_ sender: Any) {
self.checkLoginButtonValidation()
guard let idInput = self.idTextField.text else { return }
guard let passwordInput = self.passwordTextField.text else { return }
self.delegate?.determiningLoginButtonValidationRequested(id: idInput, password: passwordInput)
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
self.endEditing(true)
}

private func checkLoginButtonValidation(){
guard let idInput = self.idTextField.text else { return }
guard let passwordInput = self.passwordTextField.text else { return }
if(isInputValid(id: idInput, password: passwordInput)){
validateLoginButton()
}else{
invalidateLoginButton()
}

func isInputValid(id: String, password: String)-> Bool{
if(id.count <= 0 || password.count <= 0){
return false
}
return true
}
}

private func invalidateLoginButton(){
func invalidateLoginButton(){
guard let loginButton = self.loginButton else { return }
loginButton.isEnabled = false
}

private func validateLoginButton(){
func validateLoginButton(){
guard let loginButton = self.loginButton else { return }
loginButton.isEnabled = true
}
Expand Down