SwiftUI - Apple Sign In With Firebase

2023. 3. 14. 21:19·iOS/SwiftUI

안녕하세요 :D 망고입니다🥭

SwiftUI로 Firebase와 연동한 Apple 로그인 하는 방법에 대해 알아보겠습니다.

Firebase

Firebase 홈페이지에서 새 프로젝트를 생성하고 Authentication로 간 뒤

Sign-in-method에서 새 제공업체 추가를 누르고 Apple을 추가해준다.

 


그 다음 Xcode로 돌아와 SPM을 이용해 firebase SDK(github.com/firebase/firebase-ios-sdk.git) 를 설치한다.

PROJECT -> Package Dependencies ->  + 버튼 클릭

firebase-ios-sdk를 설치해주고

FirebaseAuth를 선택해 Add Packge해준다.

Apple

Apple 로그인을 사용하기 위해서 https://developer.apple.com/account/resources/identifiers/list 로 이동한 뒤

Identifiers에서 +버튼을 눌러 추가해준다.


 

App IDs를 클릭하고 Continue 해준다.


Description과 Bundle ID를 넣어준다.


Capabilities에서 Sign In with Apple을 선택하고 저장해준다.

 

Xcode로 돌아가 TARGETS -> Signing&Capabilities 에서 + 버튼을 눌러 Sign in with Apple을 추가해준다.

 

 

Code

import AuthenticationServices
SignInWithAppleButton { (request) in
                        loginData.nonce = randomNonceString()
                        request.requestedScopes = [.email, .fullName]
                        request.nonce = sha256(loginData.nonce)
                        
                    } onCompletion: { (result) in
                        switch result {
                        case .success(let user):
                            print("success")
                            guard let credential = user.credential as? ASAuthorizationAppleIDCredential else {
                                print("error with firebase")
                                return
                            }
                            loginData.authenticate(credential: credential)
                        case .failure(let error):
                            print(error.localizedDescription)
                        }
                    }

원하는 위치에 SignInWithAppleButton 만들어준다.


import Firebase
import CryptoKit
import AuthenticationServices
class LoginViewModel: ObservableObject {
    
    @Published var nonce = ""
    
    func authenticate(credential: ASAuthorizationAppleIDCredential) {
        //getting token
        guard let token = credential.identityToken else {
            print("error with firebase")
            return
        }
        
        guard let tokenString = String(data: token, encoding: .utf8) else {
            print("error with token")
            return
        }
        
        let firebaseCredential = OAuthProvider.credential(withProviderID: "apple.com", idToken: tokenString, rawNonce: nonce)
        Auth.auth().signIn(with: firebaseCredential) { result, err in
            if let err = err {
                print(err.localizedDescription)
            }
            
            print("로그인 완료")
        }
    }
}

// Helper for Apple Login with Firebase
func sha256(_ input: String) -> String {
    let inputData = Data(input.utf8)
    let hashedData = SHA256.hash(data: inputData)
    let hashString = hashedData.compactMap {
        String(format: "%02x", $0)
    }.joined()
    
    return hashString
}

func randomNonceString(length: Int = 32) -> String {
    precondition(length > 0)
    let charset: [Character] =
    Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
    var result = ""
    var remainingLength = length
    
    while remainingLength > 0 {
        let randoms: [UInt8] = (0 ..< 16).map { _ in
            var random: UInt8 = 0
            let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random)
            if errorCode != errSecSuccess {
                fatalError(
                    "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)"
                )
            }
            return random
        }
        
        randoms.forEach { random in
            if remainingLength == 0 {
                return
            }
            
            if random < charset.count {
                result.append(charset[Int(random)])
                remainingLength -= 1
            }
        }
    }
    
    return result
}

import SwiftUI
//import Firebase

@main
struct 앱 이름: App {
    
    //@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate 
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

/*
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        FirebaseApp.configure()
        return true
    }
}
*/

주석 처리 된 부분을 추가해준다.

 

Firebase로 가면 로그인이 된걸 확인할 수 있다.

'iOS > SwiftUI' 카테고리의 다른 글

SwiftUI - Sticky Header  (0) 2023.03.21
SwiftUI - TabView  (0) 2023.03.16
SwiftUI - System Icons  (0) 2023.03.09
SwiftUI - Gradients (Linear, Radial, Angular)  (0) 2023.03.08
SwiftUI - Navigation dismiss  (0) 2023.03.07
'iOS/SwiftUI' 카테고리의 다른 글
  • SwiftUI - Sticky Header
  • SwiftUI - TabView
  • SwiftUI - System Icons
  • SwiftUI - Gradients (Linear, Radial, Angular)
🥭Mango
🥭Mango
  • 🥭Mango
    AppleMango🥭
    🥭Mango
  • 전체
    오늘
    어제
    • 분류 전체보기
      • iOS
        • Swift
        • SwiftUI
        • RxSwift
      • Algorithm
        • C
        • Python
        • Swift
      • Computer Science
        • 컴퓨터 네트워크
        • OS
      • ...
      • 개발 타임캡슐
        • Python
        • Flutter
        • Android
        • Kotlin
        • Java
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    typing animation
    파이썬 토마토
    1613 역사
    Swift Hello World!
    스택
    백준 토마토
    파이썬
    Code Base
    MapMarker
    IOS
    Apple Login
    SwiftUI
    SwiftUI Apple Login
    1차원 뿌요뿌요
    파이썬 1459
    swiftUI tabview
    코틀린
    6118
    Custom Map Marker
    파이썬 정렬
    역사 파이썬
    코틀린 상속
    파이썬 6118
    토마토
    파이썬 14503
    14503 파이썬
    swiftUI Gradients
    14503 로봇청소기
    백준 소수
    1613 파이썬
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
🥭Mango
SwiftUI - Apple Sign In With Firebase
상단으로

티스토리툴바