UserProfileImageLoader.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. import GoogleSignIn
  24. /// An observable class for loading the current user's profile image.
  25. final class UserProfileImageLoader: ObservableObject {
  26. private let userProfile: GIDProfileData
  27. private let imageLoaderQueue = DispatchQueue(label: "com.google.days-until-birthday")
  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. imageLoaderQueue.async {
  39. #if os(iOS)
  40. let dimension = 45 * UIScreen.main.scale
  41. #elseif os(macOS)
  42. let dimension = 120
  43. #endif
  44. guard let url = userProfile.imageURL(withDimension: UInt(dimension)),
  45. let data = try? Data(contentsOf: url),
  46. let image = GIDImage(data: data) else {
  47. return
  48. }
  49. DispatchQueue.main.async {
  50. self.image = image
  51. }
  52. }
  53. }
  54. }