애플에서 제공하는 버튼컴퍼넌트가 아닌 커스텀 버튼을 사용할때 사용하는 방법
struct WindowKey: EnvironmentKey {
struct Value {
weak var value: UIWindow?
}
static let defaultValue: Value = .init(value: nil)
}
extension EnvironmentValues {
var window: UIWindow? {
get {
return self[WindowKey.self].value
}
set {
self[WindowKey.self] = .init(value: newValue)
}
}
}
import SwiftUI
import AuthenticationServices
class AppleSinginCoordinator: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
let window: UIWindow?
init(window: UIWindow?) {
self.window = window
}
func startLogin() {
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.presentationContextProvider = self
authorizationController.performRequests()
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
// Apple ID 자격 증명에서 필요한 사용자 데이터 추출하여 처리
let userID = appleIDCredential.user
let email = appleIDCredential.email
let fullName = appleIDCredential.fullName
// ...
print(appleIDCredential)
guard let appleIDToken = appleIDCredential.identityToken else {
print("Unable to fetch identity token")
return
}
guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
return
}
print(appleIDCredential.user)
print(idTokenString)
} else {
print("error")
}
}
// Apple ID 연동 실패 시
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
// Handle error.
}
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return window!
}
}
let rootView = SplashUI().environment(\.window, window)
@Environment(\.window) var window: UIWindow?
@State private var appleLoginCoordinator: AppleSinginCordinator?
// 로그인 화면 출력
appleLoginCoordinator = AppleSinginCoordinator(window: window)
appleLoginCoordinator?.startLogin()
좋은 글 감사합니다. 자주 올게요 :)