UserProfileImageLoader.swift 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 Combine
  17. import SwiftUI
  18. import GoogleSignIn
  19. /// An observable class for loading the current user's profile image.
  20. final class UserProfileImageLoader: ObservableObject {
  21. private let userProfile: GIDProfileData
  22. private let imageLoaderQueue = DispatchQueue(label: "com.google.days-until-birthday")
  23. /// A `UIImage` property containing the current user's profile image.
  24. /// - note: This will default to a placeholder, and updates will be published to subscribers.
  25. @Published var image = UIImage(named: "PlaceholderAvatar")!
  26. /// Creates an instance of this loader with provided user profile.
  27. /// - note: The instance will asynchronously fetch the image data upon creation.
  28. init(userProfile: GIDProfileData) {
  29. self.userProfile = userProfile
  30. guard userProfile.hasImage else {
  31. return
  32. }
  33. imageLoaderQueue.async {
  34. let dimension = 45 * UIScreen.main.scale
  35. guard let url = userProfile.imageURL(withDimension: UInt(dimension)),
  36. let data = try? Data(contentsOf: url),
  37. let image = UIImage(data: data) else {
  38. return
  39. }
  40. DispatchQueue.main.async {
  41. self.image = image
  42. }
  43. }
  44. }
  45. }