-
Notifications
You must be signed in to change notification settings - Fork 491
Expand file tree
/
Copy pathPhoneAuthButtonView.swift
More file actions
99 lines (94 loc) · 3 KB
/
PhoneAuthButtonView.swift
File metadata and controls
99 lines (94 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import FirebaseAuthSwiftUI
import FirebaseCore
import SwiftUI
@MainActor
public struct PhoneAuthButtonView {
@Environment(AuthService.self) private var authService
@State private var errorMessage = ""
@State private var phoneNumber = ""
@State private var showVerificationCodeInput = false
@State private var verificationCode = ""
@State private var verificationID = ""
public init() {}
}
extension PhoneAuthButtonView: View {
public var body: some View {
if authService.authenticationState != .authenticating {
VStack {
LabeledContent {
TextField("Enter phone number", text: $phoneNumber)
.textInputAutocapitalization(.never)
.disableAutocorrection(true)
.submitLabel(.next)
} label: {
Image(systemName: "at")
}.padding(.vertical, 6)
.background(Divider(), alignment: .bottom)
.padding(.bottom, 4)
Button(action: {
Task {
do {
let id = try await authService.verifyPhoneNumber(phoneNumber: phoneNumber)
verificationID = id
showVerificationCodeInput = true
} catch {
errorMessage = authService.string.localizedErrorMessage(
for: error
)
}
}
}) {
Text("Send SMS code")
.padding(.vertical, 8)
.frame(maxWidth: .infinity)
}
.disabled(!PhoneUtils.isValidPhoneNumber(phoneNumber))
.padding([.top, .bottom], 8)
.frame(maxWidth: .infinity)
.buttonStyle(.borderedProminent)
Text(errorMessage).foregroundColor(.red)
}.sheet(isPresented: $showVerificationCodeInput) {
TextField("Enter verification code", text: $verificationCode)
.keyboardType(.numberPad)
.padding()
.background(Color(.systemGray6))
.cornerRadius(8)
.padding(.horizontal)
Button(action: {
Task {
do {
try await authService.signInWithPhoneNumber(
verificationID: verificationID,
verificationCode: verificationCode
)
} catch {
errorMessage = authService.string.localizedErrorMessage(for: error)
}
showVerificationCodeInput = false
}
}) {
Text("Verify phone number and sign-in")
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.green)
.cornerRadius(8)
.padding(.horizontal)
}
}.onOpenURL { url in
authService.auth.canHandle(url)
}
} else {
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .white))
.padding(.vertical, 8)
.frame(maxWidth: .infinity)
}
Text(errorMessage).foregroundColor(.red)
}
}
#Preview {
FirebaseOptions.dummyConfigurationForPreview()
return PhoneAuthButtonView()
.environment(AuthService())
}