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

Network [#55] BaseURL 설정 및 네트워크 세팅 #56

Merged
merged 3 commits into from
Jan 14, 2024
Merged
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
40 changes: 40 additions & 0 deletions DontBe-iOS/DontBe-iOS.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
2A2671FF2B4C3AF0009D214F /* Publisher+UIControl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A2671FE2B4C3AF0009D214F /* Publisher+UIControl.swift */; };
2A2672022B4C3B44009D214F /* ViewModelType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A2672012B4C3B44009D214F /* ViewModelType.swift */; };
2A2672052B4C3C00009D214F /* CancelBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A2672042B4C3C00009D214F /* CancelBag.swift */; };
2A28453E2B531DDE0023F9B5 /* SocialLoginService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A28453D2B531DDE0023F9B5 /* SocialLoginService.swift */; };
2A2845402B531F0A0023F9B5 /* BaseResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A28453F2B531F0A0023F9B5 /* BaseResponse.swift */; };
2A2845432B5320070023F9B5 /* SocialLoginResponseDTO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A2845422B5320070023F9B5 /* SocialLoginResponseDTO.swift */; };
2A2845462B532BCB0023F9B5 /* SocialLoginRequestDTO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A2845452B532BCB0023F9B5 /* SocialLoginRequestDTO.swift */; };
2A31FF572B4F1E0400FEEED9 /* String+.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A31FF562B4F1E0400FEEED9 /* String+.swift */; };
2A31FF592B4F3A8B00FEEED9 /* UserInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A31FF582B4F3A8B00FEEED9 /* UserInfo.swift */; };
2A51AE852B4B05AA00FF770A /* SplashViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A51AE842B4B05AA00FF770A /* SplashViewController.swift */; };
Expand Down Expand Up @@ -109,6 +113,10 @@
2A2672012B4C3B44009D214F /* ViewModelType.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewModelType.swift; sourceTree = "<group>"; };
2A2672042B4C3C00009D214F /* CancelBag.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CancelBag.swift; sourceTree = "<group>"; };
2A26720D2B4C40CE009D214F /* Config.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Config.xcconfig; sourceTree = "<group>"; };
2A28453D2B531DDE0023F9B5 /* SocialLoginService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocialLoginService.swift; sourceTree = "<group>"; };
2A28453F2B531F0A0023F9B5 /* BaseResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseResponse.swift; sourceTree = "<group>"; };
2A2845422B5320070023F9B5 /* SocialLoginResponseDTO.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocialLoginResponseDTO.swift; sourceTree = "<group>"; };
2A2845452B532BCB0023F9B5 /* SocialLoginRequestDTO.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SocialLoginRequestDTO.swift; sourceTree = "<group>"; };
2A31FF562B4F1E0400FEEED9 /* String+.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+.swift"; sourceTree = "<group>"; };
2A31FF582B4F3A8B00FEEED9 /* UserInfo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserInfo.swift; sourceTree = "<group>"; };
2A51AE842B4B05AA00FF770A /* SplashViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SplashViewController.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -243,6 +251,32 @@
path = Protocol;
sourceTree = "<group>";
};
2A28453C2B531DAD0023F9B5 /* SocialLogin */ = {
isa = PBXGroup;
children = (
2A2845442B5320D60023F9B5 /* Service */,
2A2845412B531FF90023F9B5 /* DTO */,
);
path = SocialLogin;
sourceTree = "<group>";
};
2A2845412B531FF90023F9B5 /* DTO */ = {
isa = PBXGroup;
children = (
2A2845422B5320070023F9B5 /* SocialLoginResponseDTO.swift */,
2A2845452B532BCB0023F9B5 /* SocialLoginRequestDTO.swift */,
);
path = DTO;
sourceTree = "<group>";
};
2A2845442B5320D60023F9B5 /* Service */ = {
isa = PBXGroup;
children = (
2A28453D2B531DDE0023F9B5 /* SocialLoginService.swift */,
);
path = Service;
sourceTree = "<group>";
};
2A51AE832B4B05AA00FF770A /* Splash */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -494,6 +528,7 @@
3C6193022B3A773100220CEB /* Network */ = {
isa = PBXGroup;
children = (
2A28453C2B531DAD0023F9B5 /* SocialLogin */,
3C61930E2B3A787000220CEB /* Foundation */,
);
path = Network;
Expand Down Expand Up @@ -572,6 +607,7 @@
children = (
3C6193182B3A7AC700220CEB /* Config.swift */,
3C61931A2B3A7AD000220CEB /* NetworkError.swift */,
2A28453F2B531F0A0023F9B5 /* BaseResponse.swift */,
);
path = Foundation;
sourceTree = "<group>";
Expand Down Expand Up @@ -813,6 +849,7 @@
3CEE4CBD2B500A7800F506AF /* DontBeTransparencyInfoView.swift in Sources */,
2F8735422B4BE66500E55552 /* HomeViewController.swift in Sources */,
2A8D70B42B4C999F009F4C6C /* CustomButton.swift in Sources */,
2A2845432B5320070023F9B5 /* SocialLoginResponseDTO.swift in Sources */,
3C61930A2B3A781300220CEB /* ImageLiterals.swift in Sources */,
2A8D70C52B4D8079009F4C6C /* UIViewController+.swift in Sources */,
2A6D54C12B479B4300F9891E /* adjusted+.swift in Sources */,
Expand Down Expand Up @@ -866,6 +903,7 @@
2A2671FD2B4C3A9F009D214F /* LoginViewModel.swift in Sources */,
2FB818DC2B51875D00B7498F /* PostReplyCollectionViewCell.swift in Sources */,
3C6192EF2B3A719A00220CEB /* SceneDelegate.swift in Sources */,
2A2845462B532BCB0023F9B5 /* SocialLoginRequestDTO.swift in Sources */,
2AF069B42B5194F300CA3E48 /* MyPageIntroductionEditView.swift in Sources */,
2A2672052B4C3C00009D214F /* CancelBag.swift in Sources */,
2FB818D92B5186FC00B7498F /* PostReplyCollectionView.swift in Sources */,
Expand All @@ -879,12 +917,14 @@
3CF184CB2B4EEC0B00816D5F /* MyPageViewController.swift in Sources */,
3C35565B2B494F0A0016BA49 /* UIColor+.swift in Sources */,
2AF069AE2B514B0100CA3E48 /* NotificationEmptyViewCell.swift in Sources */,
2A28453E2B531DDE0023F9B5 /* SocialLoginService.swift in Sources */,
2AC9FB1B2B4DE77400D31071 /* AgreementListCustomView.swift in Sources */,
2F17418A2B500CC20089FC4D /* HomeBottomsheetView.swift in Sources */,
3C01692A2B4DC82D0075334B /* DontBePopupView.swift in Sources */,
2A2671FF2B4C3AF0009D214F /* Publisher+UIControl.swift in Sources */,
3C4993672B4F2644002A99CF /* MyPageContentViewController.swift in Sources */,
3CEE4CC22B503F9E00F506AF /* DontBeCustomInfoView.swift in Sources */,
2A2845402B531F0A0023F9B5 /* BaseResponse.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 코드 패치에는 다음과 같은 변경 사항이 있습니다:

  1. 파일 추가:

    • SocialLoginService.swift, BaseResponse.swift, SocialLoginResponseDTO.swift, SocialLoginRequestDTO.swift 파일이 소스에 추가되었습니다.
  2. 그룹 추가:

    • SocialLogin 그룹이 Network 그룹 안에 추가되었습니다.
    • DTOService 그룹이 SocialLogin 그룹 안에 추가되었습니다.

수정 사항 및 개선 제안은 제공하지 않았습니다.

Expand Down
2 changes: 1 addition & 1 deletion DontBe-iOS/DontBe-iOS/Application/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
NSAttributedString.Key.foregroundColor: UIColor.donBlack
]

KakaoSDK.initSDK(appKey: Bundle.main.object(forInfoDictionaryKey: Config.Keys.Plist.nativeAppKey) as? String ?? "")
KakaoSDK.initSDK(appKey: Config.nativeAppKey)
return true
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 코드 패치에 대한 간단한 코드 리뷰를 도와드리겠습니다. 버그 위험 및 개선 제안 사항을 언급하도록 하겠습니다:

  1. 해당 코드 패치는 AppDelegate 클래스 내의 application(_:didFinishLaunchingWithOptions:) 메서드에서 수행됩니다.
  2. 이 코드 패치에서는 KakaoSDK를 초기화하는 작업이 수행됩니다.
  3. 변경된 부분은 KakaoSDK.initSDK(appKey:) 메서드의 인수로 사용되는 앱 키입니다.
  4. 기존 코드에서는 NSBundle.main.object(forInfoDictionaryKey: Config.Keys.Plist.nativeAppKey)를 사용하여 앱 키 값을 가져왔지만, 변경된 코드에서는 Config.nativeAppKey를 사용합니다.

버그 위험:

  • 해당 코드 패치에 명시적인 버그 위험이 보이지 않습니다.

개선 제안:

  • 클래스 멤버인 Config.nativeAppKey은 미리 정의되어 있어야 합니다. nativeAppKey가 정의되지 않은 경우에 대비하는 방법을 고려해보세요.
  • Config.nativeAppKeynil이거나 유효하지 않을 경우에 대한 처리를 추가해보세요.
  • 다른 문제점이나 개선할 수 있는 사항은 제공된 정보만으로는 파악하기 어렵습니다. 전체 코드 범위 등 추가 정보를 제공한다면 더 자세한 도움을 드릴 수 있습니다.

Expand Down
8 changes: 3 additions & 5 deletions DontBe-iOS/DontBe-iOS/Application/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,18 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
self.window?.rootViewController = SplashViewController()
self.window?.makeKeyAndVisible()

DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0) {
// let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel()))
// let navigationController = UINavigationController(rootViewController: DontBeTabBarController())
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
if loadUserData()?.isSocialLogined == true && loadUserData()?.isJoinedApp == true && loadUserData()?.isOnboardingFinished == true {
let navigationController = UINavigationController(rootViewController: DontBeTabBarController())
self.window?.rootViewController = navigationController
} else if loadUserData()?.isJoinedApp == false {
let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel()))
let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel(networkProvider: SocialLoginService())))
self.window?.rootViewController = navigationController
} else if loadUserData()?.isOnboardingFinished == false {
let navigationController = UINavigationController(rootViewController: OnboardingViewController())
self.window?.rootViewController = navigationController
} else {
let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel()))
let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel(networkProvider: SocialLoginService())))
self.window?.rootViewController = navigationController
}
self.window?.makeKeyAndVisible()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아래는 코드 패치입니다. 지적해야 할 버그 위험 또는 개선 제안이 있다면 환영합니다:

@@ -19,20 +19,18 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
self.window?.rootViewController = SplashViewController()
self.window?.makeKeyAndVisible()

  • DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2.0) {
    -// let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel()))
    -// let navigationController = UINavigationController(rootViewController: DontBeTabBarController())
  • DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
    if loadUserData()?.isSocialLogined == true && loadUserData()?.isJoinedApp == true && loadUserData()?.isOnboardingFinished == true {
    let navigationController = UINavigationController(rootViewController: DontBeTabBarController())
    self.window?.rootViewController = navigationController
    } else if loadUserData()?.isJoinedApp == false {
  •        let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel()))
    
  •        let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel(networkProvider: SocialLoginService())))
           self.window?.rootViewController = navigationController
       } else if loadUserData()?.isOnboardingFinished == false {
           let navigationController = UINavigationController(rootViewController: OnboardingViewController())
           self.window?.rootViewController = navigationController
       } else {
    
  •        let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel()))
    
  •        let navigationController = UINavigationController(rootViewController: LoginViewController(viewModel: LoginViewModel(networkProvider: SocialLoginService())))
           self.window?.rootViewController = navigationController
       }
       self.window?.makeKeyAndVisible()
    

코드 리뷰를 진행하겠습니다.

  1. DispatchTime 조정: 비동기적으로 실행되는 블록의 실행 시간을 2.0초에서 1.0초로 변경했습니다.

  2. LoginViewController 인스턴스화: LoginViewController 생성자에 viewModel 매개변수 외에도 networkProvider를 추가함으로써, LoginViewModel의 의존성을 SocialLoginService로 변경했습니다. 이렇게 함으로써 더 큰 유연성을 갖출 수 있습니다.

  3. 중복 코드 제거: 원래 코드에서 두 개의 동일한 브랜치에서 LoginViewController 인스턴스화를 사용했으므로 이를 통합하여 중복을 없앴습니다.

  4. 주석 처리된 코드 제거: LoginViewController와 DontBeTabBarController를 사용하는 네비게이션 컨트롤러를 생성하는 라인의 주석 처리된 코드를 삭제했습니다.

이 코드 패치를 통해 일부 버그 위험을 해결하고 코드 구조를 개선했습니다.

Expand Down
7 changes: 7 additions & 0 deletions DontBe-iOS/DontBe-iOS/Global/Resources/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>BASE_URL</key>
<string>$(BASE_URL)</string>
<key>UIUserInterfaceStyle</key>
<string>Light</string>
<key>LSApplicationQueriesSchemes</key>

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 코드 패치에서는 NSAppTransportSecurityBASE_URL이 추가되었습니다.

향상사항:

  • NSAppTransportSecurity 딕셔너리에 NSAllowsArbitraryLoads 키가 추가되어, 앱이 모든 네트워크 연결을 허용하도록 설정됩니다. 이것은 보안상의 위험을 초래할 수 있으므로, 가능하면 특정 도메인만 허용하도록 변경하는 것이 좋습니다.
  • BASE_URL 키에는 $(BASE_URL) 문자열이 값으로 지정되어 있는데, 이는 변수 또는 환경변수의 값을 참조하는 것으로 보입니다. 값으로 실제 사용할 URL을 지정해야 합니다.

문제점:

  • 문제점은 없어 보입니다.

요약:

  • 네트워크 보안과 관련된 설정(NSAppTransportSecurity)을 조정할 필요가 있습니다.
  • BASE_URL 값을 서버의 주소로 지정해야 합니다.

Expand Down
15 changes: 15 additions & 0 deletions DontBe-iOS/DontBe-iOS/Network/Foundation/BaseResponse.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// BaseResponse.swift
// DontBe-iOS
//
// Created by 변희주 on 1/14/24.
//

import Foundation

struct BaseResponse<T: Decodable>: Decodable {
let status: Int
let success: Bool
let message: String
let data: T?
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 코드 패치는 큰 결함이 없어 보입니다. 다만, 한 가지 개선점을 제안드릴게요. 굳이 BaseResponse 구조체를 Decodable 프로토콜을 채택하도록 구현할 필요는 없습니다. 왜냐하면 BaseResponse의 속성 중 일부가 이미 Decodable이기 때문이에요. 따라서, 아래와 같이 수정하는 것이 더 간단하고 명확할 겁니다.

struct BaseResponse<T>: Decodable where T: Decodable {
    let status: Int
    let success: Bool
    let message: String
    let data: T?
}

이와 같이 수정하면 현재의 코드와 동일한 동작을 하지만, BaseResponse가 불필요하게 자기 자신을 추가적으로 해석하지 않아도 되므로 개선됩니다.

17 changes: 17 additions & 0 deletions DontBe-iOS/DontBe-iOS/Network/Foundation/Config.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ enum Config {
enum Keys {
enum Plist {
static let nativeAppKey = "NATIVE_APP_KEY"
static let baseURL = "BASE_URL"
}
}

Expand All @@ -21,3 +22,19 @@ enum Config {
return dictionary
}()
}

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

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 코드 패치는 Config라는 열거형과 Keys 안에 Plist라는 열거형이 정의되어 있습니다. 그리고 nativeAppKeybaseURL이라는 두 개의 속성도 추가되었습니다.

주의해야 할 부분은 nativeAppKeybaseURL의 값을 가져오는 부분입니다. Config에 해당하는 infoDictionary에서 Keys.Plist.nativeAppKeyKeys.Plist.baseURL에 해당하는 값을 가져옵니다. 하지만 해당 값이 없는 경우, fatalError를 발생시키며 "Base URL is not set in plist for this configuration"라는 메시지를 표시합니다.

개선 사항으로는 fatalError 대신 선택적인 반환을 사용하여 앱이 비정상 종료되지 않게 처리할 수 있습니다. 또한, 선택적인 반환을 위해 옵셔널 타입을 사용하면 유효하지 않은 속성이 있더라도 코드 실행을 계속할 수 있습니다.

아래는 개선된 코드의 예시입니다:

extension Config {
    static var nativeAppKey: String? {
        return Config.infoDictionary[Keys.Plist.nativeAppKey] as? String
    }
    
    static var baseURL: String? {
        return Config.infoDictionary[Keys.Plist.baseURL] as? String
    }
}

이렇게 구현하면 nativeAppKeybaseURL은 옵셔널 타입으로 선언되기 때문에 값이 없을 경우에도 안전하게 처리할 수 있습니다.

19 changes: 18 additions & 1 deletion DontBe-iOS/DontBe-iOS/Network/Foundation/NetworkError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@

import UIKit

enum NetworkError {
enum NetworkError: Int, Error, CustomStringConvertible {
var description: String { self.errorDescription }
case responseError
case badRequestError = 400
case unautohorizedError = 401
case notFoundError = 404
case internalServerError = 500
case unknownError

var errorDescription: String {
switch self {
case .responseError: return "REQUEST_ERROR"
case .badRequestError: return "BAD_REQUEST_ERROR"
case .unautohorizedError: return "UNAUTHORIZED_ERROR"
case .notFoundError: return "NOT_FOUND_ERROR"
case .internalServerError: return "SERVER_ERROR"
case .unknownError: return "UNKNOWN_ERROR"
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3
에러 코드 정리 고생하셨어요~~

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//
// SocialLoginRequestDTO.swift
// DontBe-iOS
//
// Created by 변희주 on 1/14/24.
//

import Foundation

struct SocialLoginRequestDTO: Encodable {
let socialPlatform: String
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//
// SocialLoginResponseDTO.swift
// DontBe-iOS
//
// Created by 변희주 on 1/14/24.
//

import Foundation

// MARK: - SocilLoginResponseDTO
struct SocialLoginResponseDTO: Decodable {
let nickName: String
let memberId: Int
let accessToken, refreshToken: String
let memberProfileUrl: String
let isNewUser: Bool
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//
// KakaoLoginService.swift
// DontBe-iOS
//
// Created by 변희주 on 1/14/24.
//

import Foundation
import Foundation

protocol SocialLoginServiceType {
func makeRequestURL(accessToken: String) -> URLRequest
func postData(accessToken: String) async throws -> BaseResponse<SocialLoginResponseDTO>?
func parseData(data: Data) -> BaseResponse<SocialLoginResponseDTO>?
}

final class SocialLoginService: SocialLoginServiceType {

func makeRequestURL(accessToken: String) -> URLRequest {

let baseURL = Config.baseURL

let urlString = "\(baseURL)/auth"

// URL 생성
guard let url = URL(string: urlString) else {
fatalError("Failed to create URL")
}

// URLRequest 생성
var request = URLRequest(url: url)
request.httpMethod = "POST"

// 헤더 추가
let header = ["Content-Type": "application/json",
"Authorization": "Bearer \(accessToken)"]
header.forEach {
request.addValue($0.value, forHTTPHeaderField: $0.key)
}

// 리퀘스트 바디 설정
let requestBody = SocialLoginRequestDTO(socialPlatform: "KAKAO")
do {
let jsonData = try JSONEncoder().encode(requestBody)
request.httpBody = jsonData
} catch {
print("Failed to encode request body: \(error)")
}

return request
}

func postData(accessToken: String) async throws -> BaseResponse<SocialLoginResponseDTO>? {
do {
let request = self.makeRequestURL(accessToken: accessToken)
let (data, response) = try await URLSession.shared.data(for: request)

guard let httpResponse = response as? HTTPURLResponse else {
throw NetworkError.responseError
}

switch httpResponse.statusCode {
case 200..<300:
return parseData(data: data)
case 400:
throw NetworkError.badRequestError
case 401:
throw NetworkError.unautohorizedError
case 404:
throw NetworkError.notFoundError
case 500:
throw NetworkError.internalServerError
default:
throw NetworkError.unknownError
}
} catch {
throw error
}
}

func parseData(data: Data) -> BaseResponse<SocialLoginResponseDTO>? {
do {
let jsonDecoder = JSONDecoder()
let result = try jsonDecoder.decode(BaseResponse<SocialLoginResponseDTO>.self, from: data)
return result
} catch {
print(error)
return nil
}
}
}
1 change: 0 additions & 1 deletion DontBe-iOS/DontBe-iOS/Presentation/Helpers/UserInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import Foundation
struct UserInfo: Codable {
let isSocialLogined: Bool
let isJoinedApp: Bool
let isNotFirstUser: Bool
let isOnboardingFinished: Bool
let userNickname: String
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,11 @@ extension JoinProfileViewController {
} else {
saveUserData(UserInfo(isSocialLogined: true,
isJoinedApp: true,
isNotFirstUser: false,
isOnboardingFinished: false,
userNickname: self.originView.nickNameTextField.text ?? ""))

let viewContoller = OnboardingViewController()
viewContoller.originView.isFirstUser = true
self.navigationBackButton.removeFromSuperview()
self.navigationController?.pushViewController(viewContoller, animated: true)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,24 +113,18 @@ extension LoginViewController {
let output = self.viewModel.transform(from: input, cancelBag: self.cancelBag)

output.userInfoPublisher
// .receive(on: RunLoop.main)
.sink { userInfo in
print(userInfo)
// 서버통신 -> 첫 로그인 유저면 여기
let viewController = JoinAgreementViewController(viewModel: JoinAgreeViewModel())
saveUserData(UserInfo(isSocialLogined: true,
isJoinedApp: false,
isNotFirstUser: false,
isOnboardingFinished: false,
userNickname: ""))
// 서버통신 -> 이미 로그인 유저면
// let viewController = OnboardingViewController()
// saveUserData(UserInfo(isSocialLogined: true,
// isJoinedApp: true,
// isNotFirstUser: true,
// isOnboardingFinished: false,
// userNickname: ""))
self.navigationController?.pushViewController(viewController, animated: true)
.receive(on: RunLoop.main)
.sink { isFirstUser in
if isFirstUser {
// 첫 로그인 유저면 여기
let viewController = JoinAgreementViewController(viewModel: JoinAgreeViewModel())
self.navigationController?.pushViewController(viewController, animated: true)
} else {
// 이미 가입한 유저면 여기
let viewController = OnboardingViewController()
viewController.originView.isFirstUser = false
self.navigationController?.pushViewController(viewController, animated: true)
}
}
.store(in: self.cancelBag)
}
Expand Down
Loading