Swift: Phone Number/SMS Auth Tutorial (Xcode, Firebase, iOS) – 2022 Tutorial
public func startAuth(phomeNumber: String, completion: @escaping (Result<Bool, Error>) -> ()) {
PhoneAuthProvider.provider().verifyPhoneNumber(phomeNumber, uiDelegate: nil) { [weak self] verificationID, error in
guard
let verificationID = verificationID,
error == nil else {
completion(.failure(AuthError.verificationDidFail))
return
}
self?.verificationID = verificationID
completion(.success(true))
}
}
public func verifyCode(smsCode: String, completion: @escaping (Result<Bool, Error>) -> ()) {
guard let verificationID = verificationID else {
completion(.failure(AuthError.verificationDidFail))
return
}
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: smsCode)
auth.signIn(with: credential) { result, error in
guard error == nil else {
completion(.failure(AuthError.signInDidFail))
return
}
completion(.success(true))
}
}
credential
을 생성한 뒤 해당 데이터로 파이어베이스 로그인signIn
컴플리션 핸들러로부터 얻어지는 로그인 여부 및 에러를 컴플리션 핸들러로 전달, 뷰 전환에 사용func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let scene = (scene as? UIWindowScene) else { return }
let window = UIWindow(windowScene: scene)
window.makeKeyAndVisible()
let homeVC = HomeViewController()
let navVC = UINavigationController(rootViewController: homeVC)
window.rootViewController = navVC
if Auth.auth().currentUser == nil {
let phoneVC = PhoneAuthViewController()
let phoneNavVC = UINavigationController(rootViewController: phoneVC)
phoneNavVC.modalPresentationStyle = .fullScreen
navVC.present(phoneNavVC, animated: false)
}
self.window = window
}
@objc private func didTapVerify() {
guard
let smsCode = smsCodeTextField.text,
!smsCode.isEmpty else {
resultLabel.text = "Check your sms code..."
return
}
authManager.verifyCode(smsCode: smsCode) { [weak self] result in
DispatchQueue.main.async { [weak self] in
switch result {
case .success(let success):
if !success {
self?.resultLabel.text = "Your verification code is wrong"
} else {
self?.dismiss(animated: true)
}
case .failure(let error): self?.resultLabel.text = error.localizedDescription
}
}
}
}