UserProfileImageLoader.swift 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. #if os(iOS)
  17. typealias GIDImage = UIImage
  18. #elseif os(macOS)
  19. typealias GIDImage = NSImage
  20. #endif
  21. import Combine
  22. import SwiftUI
  23. @preconcurrency import GoogleSignIn
  24. /// An observable class for loading the current user's profile image.
  25. @MainActor final class UserProfileImageLoader: ObservableObject {
  26. private let userProfile: GIDProfileData
  27. private var imageLoadingTask: Task<Void, Never>?
  28. /// A `UIImage` property containing the current user's profile image.
  29. /// - note: This will default to a placeholder, and updates will be published to subscribers.
  30. @Published var image = GIDImage(named: "PlaceholderAvatar")!
  31. /// Creates an instance of this loader with provided user profile.
  32. /// - note: The instance will asynchronously fetch the image data upon creation.
  33. init(userProfile: GIDProfileData) {
  34. self.userProfile = userProfile
  35. guard userProfile.hasImage else {
  36. return
  37. }
  38. imageLoadingTask = Task {
  39. await loadProfileImage()
  40. }
  41. }
  42. private func loadProfileImage() async {
  43. #if os(iOS)
  44. let dimension = 45 * UIScreen.main.scale
  45. #elseif os(macOS)
  46. let dimension = 120
  47. #endif
  48. guard let url = userProfile.imageURL(withDimension: UInt(dimension)) else {
  49. return
  50. }
  51. do {
  52. let (imageData, _) = try await URLSession.shared.data(from: url)
  53. if let image = GIDImage(data: imageData) {
  54. self.image = image
  55. }
  56. } catch {
  57. print("Image download failed:", error)
  58. }
  59. }
  60. deinit {
  61. imageLoadingTask?.cancel()
  62. }
  63. }