본문 바로가기

iOS/UIKit

[iOS] Apple Login 구현하기 (MVVM)

728x90
반응형

오늘은 Apple Login을 MVVM 구조로 구현해보려 합니다.
먼저, Apple Login을 하기 위해서는 개발자 계정이 필요합니다.

1. Set the bundle ID

https://appstoreconnect.apple.com/apps
위 사이트에 로그인 한 후, 앱 옆에 + 버튼 -> 신규 앱을 누르면 다음과 같은 화면이 나옵니다.

 

https://appstoreconnect.apple.com/login?targetUrl=%2Fapps&authResult=FAILED

 

appstoreconnect.apple.com

image

인증서, 식별자 및 프로파일을 클릭해줍시다.

image

Bundle ID를 입력한 후

image

아래에 있는 Sign In with Apple 항목에 체크해줍시다.

image

이제 ID를 등록하였습니다.

2. MVC로 구현

https://developer.apple.com/documentation/authenticationservices/implementing_user_authentication_with_sign_in_with_apple
공식문서에 자세히 설명되어 있습니다.

 

Implementing User Authentication with Sign in with Apple | Apple Developer Documentation

Provide a way for users of your app to set up an account and start using your services.

developer.apple.com

이 방식은 iOS 13, iPadOS 13, Xcode 11.3 이상의 버전에서 사용가능합니다.

먼저 LoginViewController를 생성해주고, 버튼을 눌러서 Apple Login을 하도록 구현하였습니다.
UI는 간단하게 스토리보드로 구현하였습니다.

먼저 AuthenticationServices을 import 해주어야합니다.
그 이후, 버튼이 눌렸을 때 다음과 같이 작성해줍시다.

image

ASAuthorizationController의 delegate를 self로 주었기 때문에,
ASAuthorizationControllerDelegate를 LoginViewController가 채택해주어야 합니다.

그 이후, 다음 두개의 메시지를 가지고 로그인이 성공하는지, 실패하는지 alert을 띄워줍시다.

image

마지막으로 Target에 들어가서 설정해줍시다.

imageimage

실행

ezgif com-resize

전체 코드

3. MVVM로 구현

먼저 ViewModelinputoutput을 프로토콜로 정의하였습니다.

image

input로그인 버튼이 눌렸을 때, 작동할 함수를 넣어주었습니다.
output으로는 view와 viewModel간의 데이터 바인딩을 하기 위한 subject를 넣어주었습니다.

이제 ViewModel이 이 프로토콜을 채택하고 있도록 구현하였습니다.

image

기존에 ViewController에서 Apple Login을 담당하던 로직을 ViewModel로 옮기고 싶어서 따로 빼주었습니다.
ViewModel에 AuthenticationServices를 import해주었고, ASAuthorizationControllerDelegate를 채택하였습니다.

image

그런데.. NSObject를 상속해야 한다고 하네요. 일단 Fix를 눌러봅시다.

image


...

엄청 많은 프로퍼티를 작성해주어야 하네요.

UIViewController에 상속했을 때는 괜찮았는데 왜 그럴까하고 알아보았는데
UIViewControllerUIResponder, NSCoding, UIAppearanceContainer, UITraitEnvironment, UIContentContainer, UIFocusEnvironment를 상속받고 있는데 그중에서도 UIReponder는 NSObject를 상속받고 있기 때문인 것 같습니다.

imageimage

그래서 LoginViewModelNSObject를 상속받도록 구현하였고, 상속받은 프로퍼티를 덮어 쓰도록 init을 override 하였습니다.

image

alert을 띄우는 부분 제외하고 ViewController에서 작성했던 로직을 ViewModel에 작성해주었습니다.

image

이제 성공했을 때와 실패했을 때 Subject를 통해서 값을 방출시키려고 합니다.

image

이제 ViewController의 코드도 수정해줍시다.
AuthenticationServices도 import 할 필요가 없어졌습니다.
ViewModel을 생성하고, 버튼이 눌릴때 ViewModel에게 버튼이 눌렸음을 알려줍니다.

image

이제 bind 함수를 작성하고, 성공/실패 여부에 따라 ViewController에서 alert을 띄우도록 합시다.

image

정상적으로 동작하는 것을 확인하였습니다.

전체 코드

728x90
반응형