UserProfileView.swift 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright 2021 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import SwiftUI
  17. import GoogleSignIn
  18. struct UserProfileView: View {
  19. @EnvironmentObject var authViewModel: AuthenticationViewModel
  20. @StateObject var birthdayViewModel = BirthdayViewModel()
  21. private var user: GIDGoogleUser? {
  22. return GIDSignIn.sharedInstance.currentUser
  23. }
  24. var body: some View {
  25. return Group {
  26. if let userProfile = user?.profile {
  27. VStack(spacing: 10) {
  28. HStack(alignment: .top) {
  29. UserProfileImageView(userProfile: userProfile)
  30. .padding(.leading)
  31. VStack(alignment: .leading) {
  32. Text(userProfile.name)
  33. .font(.headline)
  34. Text(userProfile.email)
  35. }
  36. }
  37. NavigationLink(
  38. NSLocalizedString("View Days Until Birthday", comment: "View birthday days"),
  39. destination: BirthdayView(birthdayViewModel: birthdayViewModel)
  40. .onAppear {
  41. guard self.birthdayViewModel.birthday != nil else {
  42. if !self.authViewModel.hasBirthdayReadScope {
  43. guard let viewController = UIApplication.shared.windows.first?.rootViewController else {
  44. print("There was no root view controller")
  45. return
  46. }
  47. Task { @MainActor in
  48. do {
  49. let signInResult = try await authViewModel.addBirthdayReadScope(
  50. viewController: viewController
  51. )
  52. self.authViewModel.state = .signedIn(signInResult.user)
  53. self.birthdayViewModel.fetchBirthday()
  54. } catch {
  55. print("Failed to fetch birthday: \(error)")
  56. }
  57. }
  58. } else {
  59. self.birthdayViewModel.fetchBirthday()
  60. }
  61. return
  62. }
  63. })
  64. Spacer()
  65. }
  66. .toolbar {
  67. ToolbarItemGroup(placement: .navigationBarTrailing) {
  68. Button(
  69. NSLocalizedString("Disconnect", comment: "Disconnect button"),
  70. action: authViewModel.disconnect
  71. )
  72. Button(
  73. NSLocalizedString("Sign Out", comment: "Sign out button"),
  74. action: authViewModel.signOut
  75. )
  76. }
  77. }
  78. } else {
  79. Text(NSLocalizedString("Failed to get user profile!", comment: "Empty user profile text"))
  80. }
  81. }
  82. }
  83. }