나의 발자취

[SwiftUI] Social Login 기능 도입하기 - Apple 본문

앱 개발/iOS

[SwiftUI] Social Login 기능 도입하기 - Apple

달모드 2024. 11. 26. 11:32

+ Capability를 클릭해서 Sign in with Apple ID를 클릭한다.

 

 

 

그리고 새 SwiftUI 뷰를 만들어준다.SignInWithAppleView.swift 

 

import 후에 아래 SignInWithAppleButton()메서드를 임포트해준다. (label 생성자가 있는걸로)

 

 

기본값은 signIn이다.

 

 

 

 

success문은 이렇게 써준다.

case .success(let auth):
                    if let credential = auth.credential as?
                        ASAuthorizationAppleIDCredential {
                        let userId = credential.user
                        let email = credential.email
                        let fullName = credential.fullName
                    }

 

 

.failure문은 이렇게

case .failure(let error):
                        print("Failed to sign in with Apple: \(error.localizedDescription)")

 

 

마지막으로 버튼 크기를 조정해주면 완성

 


버튼 여러개 생성을 위한 모듈화하기

이 영역들은 함수기에 코드 스니펫으로 만들어서 또 다르게 활용해줄것이다.

 

 

body View 컨테이너 아래에다가 함수를 만들어줄건데, request의 타입은 위 SignInWithAppleButton 메서드가 따르는 타입인 ASAuthrizationAppleIDRequest이기 때문에 그대로 해준다.

func configureRequest(request: ASAuthorizationAppleIDRequest){
        request.requestedScopes = [.email, .fullName]
    }

 

 

그리고 그 아래에 switch문을 긁어서 넣어준다.

    func handleAuthorization(result: Result<ASAuthorization, Error>){
        switch result {
        case .success(let auth):
            if let credential = auth.credential as?
                ASAuthorizationAppleIDCredential {
                let userId = credential.user
                let email = credential.email
                let fullName = credential.fullName
            }
        case .failure(let error):
            print("Failed to sign in with Apple: \(error.localizedDescription)")
            
        }
    }

 

이렇게

 

 

 

이제 얘들이 로컬 지역변수니까 @State로 선언을 해준다.\

 

그럼 아래에 기존에 썼던 변수는 let에서 self.로 변경을 해주어야한다.

마지막 fullName의 경우는 String type이 아니라서 에러가 나는 것이다. (일단 주석처리)

 

 

그러고 나서 버튼을 세 개 붙여넣어준다.

 

SignInWithAppleView.swift

import SwiftUI
import AuthenticationServices

struct SignInWithAppleView: View {
    @State var userId: String?
    @State var fulllName: PersonNameComponents?
    @State var email: String?
    var body: some View {
        VStack {
            Text("Social Login Demo").font(.largeTitle).fontWeight(.bold).padding()
            if let userId {
                VStack {
                    Text("User ID: \(userId)")
                    if let email {
                        Text("Email: \(email)")
                    }
                    if let fulllName {
                        Text("Full Name: \(fulllName.familyName!) \(fulllName.givenName!)")
                    }
                    
                }
                
            }
            SignInWithAppleButton(.signIn,
                                  onRequest: configureRequest,
                                  onCompletion:handleAuthorization)
            .frame(height:50).padding(.horizontal, 20)
            
            
            SignInWithAppleButton(.signIn,
                                  onRequest: configureRequest,
                                  onCompletion:handleAuthorization)
            .frame(height:50).padding(.horizontal, 20)
            
            
            SignInWithAppleButton(.signIn,
                                  onRequest: configureRequest,
                                  onCompletion:handleAuthorization)
            .frame(height:50).padding(.horizontal, 20)

        }
    }
    
    func configureRequest(request: ASAuthorizationAppleIDRequest){
        request.requestedScopes = [.email, .fullName]
    }
    
    func handleAuthorization(result: Result<ASAuthorization, Error>){
        switch result {
        case .success(let auth):
            if let credential = auth.credential as?
                ASAuthorizationAppleIDCredential {
                self.userId = credential.user
                self.email = credential.email
//                self.fullName = credential.fullName
            }
        case .failure(let error):
            print("Failed to sign in with Apple: \(error.localizedDescription)")
            
        }
    }
}

#Preview {
    SignInWithAppleView()
}

 

 

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            SignInWithAppleView()
        }
        .padding()
    }
}

#Preview {
    ContentView()
}

코드를 작성해주고 시뮬레이터에서 실행해주면 로그인이 정상적으로 되는것이 확인된다!

 

Comments