SwiftUI Apple Login 구현 방법

작성일 :

SwiftUI Apple Login 구현 방법

Apple 로그인은 사용자의 Apple ID를 이용하여 간편하고 안전하게 로그인할 수 있는 기능입니다. Apple은 2019년 WWDC에서 새로운 인증 방식인 Sign in with Apple을 발표했는데, 이를 사용하면 사용자는 더 나은 개인정보 보호와 간편한 사용성을 누릴 수 있습니다. 이 글에서는 SwiftUI 환경에서 Apple 로그인을 구현하는 과정을 단계별로 설명하겠습니다.

Apple 로그인 설정

Apple 로그인을 구현하기 전에, 먼저 Xcode 프로젝트 설정을 해야 합니다. Xcode 프로젝트에 Apple 로그인 기능을 추가하려면 다음 단계를 따르세요.

  1. Xcode 프로젝트 열기: Xcode에서 프로젝트를 엽니다.
  2. Signing & Capabilities 설정: 프로젝트 설정에서 'Signing & Capabilities' 탭을 선택합니다. '+' 버튼을 클릭하고 'Sign in with Apple'을 추가합니다.
  3. Keychain Sharing 활성화: Apple 로그인을 사용하려면 'Keychain Sharing'도 활성화해야 합니다. '+' 버튼을 클릭하고 'Keychain Sharing'을 선택하여 추가합니다.

Apple Developer 계정 설정

Apple 로그인을 사용하기 위해서는 Apple Developer 계정이 필요합니다. Apple Developer 계정을 통해 앱의 Bundle Identifier와 관련된 인증키와 권한을 설정해야 합니다. 다음 단계를 따르세요.

  1. Apple Developer 계정 로그인: 🔗 Apple Developer 계정에 로그인합니다.
  2. Certificates, Identifiers & Profiles: 'Certificates, Identifiers & Profiles' 섹션에서 앱의 Bundle Identifier을 선택합니다.
  3. Sign in with Apple 활성화: 'Capabilities' 탭에서 'Sign in with Apple'을 찾아서 활성화합니다.

SwiftUI에서 Apple 로그인 버튼 추가

Xcode 프로젝트와 Apple Developer 계정 설정이 완료되면 이제 SwiftUI에서 Apple 로그인 버튼을 추가할 수 있습니다. 다음 코드는 SwiftUI 뷰에 Apple 로그인 버튼을 추가하는 기본 예제입니다.

swift
import SwiftUI
import AuthenticationServices

struct ContentView: View {
    var body: some View {
        SignInWithAppleButton(
            onRequest: { request in
                request.requestedScopes = [.fullName, .email]
            },
            onCompletion: { result in
                switch result {
                case .success(let authResults):
                    print("Authorization successful.")
                    handleAuthorization(authResults)
                case .failure(let error):
                    print("Authorization failed: \(error.localizedDescription)")
                }
            }
        )
        .signInWithAppleButtonStyle(.black)
        .frame(width: 200, height: 40)
        .padding()
    }

    func handleAuthorization(_ authResults: ASAuthorization) {
        // 사용자 정보 처리
    }
}

이 코드는 SignInWithAppleButton을 사용하여 Apple 로그인 버튼을 SwiftUI 뷰에 추가합니다. onRequestonCompletion 클로저를 사용하여 요청과 결과를 처리할 수 있습니다. onRequest 클로저에서는 로그인 요청 시 필요한 사용자 정보(예: 이름, 이메일)를 지정하고, onCompletion 클로저에서는 로그인 결과를 처리하면 됩니다.

인증 결과 처리

Apple 로그인 인증 결과를 처리하려면 ASAuthorizationControllerDelegate 프로토콜을 구현해야 합니다. 인증 성공 시 사용자 정보를 받아와서 처리할 수 있습니다. 다음은 인증 결과를 처리하는 예제입니다.

swift
import AuthenticationServices

class AppleSignInCoordinator: NSObject, ASAuthorizationControllerDelegate {
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            let userIdentifier = appleIDCredential.user
            let fullName = appleIDCredential.fullName
            let email = appleIDCredential.email

            // 사용자 정보를 저장하거나 처리합니다.
        }
    }

    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        print("Authorization failed: \(error.localizedDescription)")
    }
}

이 코드에서는 authorizationController(:didCompleteWithAuthorization:) 메서드를 통해 Apple ID 자격 증명을 처리합니다. 성공적으로 인증되면 사용자 식별자(userIdentifier), 전체 이름(fullName), 이메일(email) 등의 정보를 얻을 수 있습니다.

데이터를 Keychain에 저장

Apple 로그인을 사용하면 Apple에서 제공한 사용자 식별자를 Keychain에 저장하여 다시 로그인할 때 사용할 수 있습니다. 이를 통해 사용자는 앱을 다시 열 때마다 로그인 상태를 유지할 수 있습니다. 다음은 사용자 식별자를 Keychain에 저장하는 예제입니다.

swift
import Security

func saveUserIdentifierToKeychain(_ userIdentifier: String) {
    let data = Data(userIdentifier.utf8)
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrAccount as String: "userIdentifier",
        kSecValueData as String: data
    ]
    SecItemAdd(query as CFDictionary, nil)
}

func getUserIdentifierFromKeychain() -> String? {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrAccount as String: "userIdentifier",
        kSecReturnData as String: true,
        kSecMatchLimit as String: kSecMatchLimitOne
    ]
    var dataTypeRef: AnyObject? = nil
    let status = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)
    if status == errSecSuccess, let data = dataTypeRef as? Data {
        return String(data: data, encoding: .utf8)
    }
    return nil
}

이 코드는 사용자 식별자를 Keychain에 저장하고 검색하는 함수들을 구현합니다. saveUserIdentifierToKeychain 함수는 사용자 식별자를 Keychain에 저장하고, getUserIdentifierFromKeychain 함수는 Keychain에서 사용자 식별자를 검색하여 반환합니다.

결론

이번 글에서는 SwiftUI를 사용하여 Apple 로그인 기능을 구현하는 방법을 다루었습니다. Apple 로그인을 설정하는 방법, SwiftUI에서 Apple 로그인 버튼을 추가하는 방법, 인증 결과를 처리하는 방법, 그리고 Keychain을 이용해 사용자 식별자를 저장하고 검색하는 방법에 대해 설명했습니다. 이 지침을 따라하면 사용자에게 안전하고 간편한 로그인 경험을 제공할 수 있습니다.