Extensions.swift 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import FirebaseAuth
  15. import SwiftUI
  16. import UIKit
  17. // MARK: - Extending a `Firebase User` to conform to `DataSourceProvidable`
  18. extension User: DataSourceProvidable {
  19. private var infoSection: Section {
  20. let items = [Item(title: providerID, detailTitle: "Provider ID"),
  21. Item(title: uid, detailTitle: "UUID"),
  22. Item(title: displayName ?? "––", detailTitle: "Display Name", isEditable: true),
  23. Item(
  24. title: photoURL?.absoluteString ?? "––",
  25. detailTitle: "Photo URL",
  26. isEditable: true
  27. ),
  28. Item(title: email ?? "––", detailTitle: "Email", isEditable: true),
  29. Item(title: phoneNumber ?? "––", detailTitle: "Phone Number", isEditable: true)]
  30. return Section(headerDescription: "Info", items: items)
  31. }
  32. private var metaDataSection: Section {
  33. let metadataRows = [
  34. Item(title: metadata.lastSignInDate?.description, detailTitle: "Last Sign-in Date"),
  35. Item(title: metadata.creationDate?.description, detailTitle: "Creation Date"),
  36. ]
  37. return Section(headerDescription: "Firebase Metadata", items: metadataRows)
  38. }
  39. private var otherSection: Section {
  40. let otherRows = [Item(title: isAnonymous ? "Yes" : "No", detailTitle: "Is User Anonymous?"),
  41. Item(title: isEmailVerified ? "Yes" : "No", detailTitle: "Is Email Verified?")]
  42. return Section(headerDescription: "Other", items: otherRows)
  43. }
  44. private var actionSection: Section {
  45. let actionsRows = [
  46. Item(title: UserAction.refreshUserInfo.rawValue, textColor: .systemBlue),
  47. Item(title: UserAction.signOut.rawValue, textColor: .systemBlue),
  48. Item(title: UserAction.link.rawValue, textColor: .systemBlue, hasNestedContent: true),
  49. Item(title: UserAction.requestVerifyEmail.rawValue, textColor: .systemBlue),
  50. Item(title: UserAction.updatePassword.rawValue, textColor: .systemBlue),
  51. Item(title: UserAction.tokenRefresh.rawValue, textColor: .systemBlue),
  52. Item(title: UserAction.tokenRefreshAsync.rawValue, textColor: .systemBlue),
  53. Item(title: UserAction.delete.rawValue, textColor: .systemRed),
  54. ]
  55. return Section(headerDescription: "Actions", items: actionsRows)
  56. }
  57. var sections: [Section] {
  58. [infoSection, metaDataSection, otherSection, actionSection]
  59. }
  60. }
  61. // MARK: - UIKit Extensions
  62. public extension UIViewController {
  63. func displayInfo(title: String, message: String, style: UIAlertController.Style) {
  64. let alert = UIAlertController(title: title, message: message, preferredStyle: style)
  65. alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
  66. DispatchQueue.main.async { // Ensure UI updates on the main thread
  67. self.present(alert, animated: true, completion: nil)
  68. }
  69. }
  70. @MainActor func displayError(_ error: (any Error)?, from function: StaticString = #function) {
  71. guard let error = error else { return }
  72. print("ⓧ Error in \(function): \(error.localizedDescription)")
  73. let message = "\(error.localizedDescription)\n\n Occurred in \(function)"
  74. let errorAlertController = UIAlertController(
  75. title: "Error",
  76. message: message,
  77. preferredStyle: .alert
  78. )
  79. errorAlertController.addAction(UIAlertAction(title: "OK", style: .default))
  80. present(errorAlertController, animated: true, completion: nil)
  81. }
  82. }
  83. extension UINavigationController {
  84. func configureTabBar(title: String, systemImageName: String) {
  85. let tabBarItemImage = UIImage(systemName: systemImageName)
  86. tabBarItem = UITabBarItem(title: title,
  87. image: tabBarItemImage?.withRenderingMode(.alwaysTemplate),
  88. selectedImage: tabBarItemImage)
  89. }
  90. enum titleType: CaseIterable {
  91. case regular, large
  92. }
  93. func setTitleColor(_ color: UIColor, _ types: [titleType] = titleType.allCases) {
  94. if types.contains(.regular) {
  95. navigationBar.titleTextAttributes = [.foregroundColor: color]
  96. }
  97. if types.contains(.large) {
  98. navigationBar.largeTitleTextAttributes = [.foregroundColor: color]
  99. }
  100. }
  101. }
  102. extension UITextField {
  103. func setImage(_ image: UIImage?) {
  104. guard let image = image else { return }
  105. let imageView = UIImageView(image: image)
  106. imageView.frame = CGRect(x: 10, y: 10, width: 20, height: 20)
  107. imageView.contentMode = .scaleAspectFit
  108. let containerView = UIView()
  109. containerView.frame = CGRect(x: 20, y: 0, width: 40, height: 40)
  110. containerView.addSubview(imageView)
  111. leftView = containerView
  112. leftViewMode = .always
  113. }
  114. }
  115. extension UIImageView {
  116. convenience init(systemImageName: String, tintColor: UIColor? = nil) {
  117. var systemImage = UIImage(systemName: systemImageName)
  118. if let tintColor = tintColor {
  119. systemImage = systemImage?.withTintColor(tintColor, renderingMode: .alwaysOriginal)
  120. }
  121. self.init(image: systemImage)
  122. }
  123. func setImage(from url: URL?) {
  124. guard let url = url else { return }
  125. DispatchQueue.global(qos: .background).async {
  126. guard let data = try? Data(contentsOf: url) else { return }
  127. let image = UIImage(data: data)
  128. DispatchQueue.main.async {
  129. self.image = image
  130. self.contentMode = .scaleAspectFit
  131. }
  132. }
  133. }
  134. }
  135. extension UIImage {
  136. static func systemImage(_ systemName: String, tintColor: UIColor) -> UIImage? {
  137. let systemImage = UIImage(systemName: systemName)
  138. return systemImage?.withTintColor(tintColor, renderingMode: .alwaysOriginal)
  139. }
  140. }
  141. extension UIColor {
  142. static let highlightedLabel = UIColor.label.withAlphaComponent(0.8)
  143. var highlighted: UIColor { withAlphaComponent(0.8) }
  144. var image: UIImage {
  145. let pixel = CGSize(width: 1, height: 1)
  146. return UIGraphicsImageRenderer(size: pixel).image { context in
  147. self.setFill()
  148. context.fill(CGRect(origin: .zero, size: pixel))
  149. }
  150. }
  151. }
  152. // MARK: UINavigationBar + UserDisplayable Protocol
  153. protocol UserDisplayable {
  154. func addProfilePic(_ imageView: UIImageView)
  155. }
  156. extension UINavigationBar: UserDisplayable {
  157. func addProfilePic(_ imageView: UIImageView) {
  158. let length = frame.height * 0.46
  159. imageView.clipsToBounds = true
  160. imageView.layer.cornerRadius = length / 2
  161. imageView.translatesAutoresizingMaskIntoConstraints = false
  162. addSubview(imageView)
  163. NSLayoutConstraint.activate([
  164. imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -15),
  165. imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5),
  166. imageView.heightAnchor.constraint(equalToConstant: length),
  167. imageView.widthAnchor.constraint(equalToConstant: length),
  168. ])
  169. }
  170. }
  171. // MARK: Extending UITabBarController to work with custom transition animator
  172. extension UITabBarController: UITabBarControllerDelegate {
  173. public func tabBarController(_ tabBarController: UITabBarController,
  174. animationControllerForTransitionFrom fromVC: UIViewController,
  175. to toVC: UIViewController)
  176. -> (any UIViewControllerAnimatedTransitioning)? {
  177. let fromIndex = tabBarController.viewControllers!.firstIndex(of: fromVC)!
  178. let toIndex = tabBarController.viewControllers!.firstIndex(of: toVC)!
  179. let direction: Animator.TransitionDirection = fromIndex < toIndex ? .right : .left
  180. return Animator(direction)
  181. }
  182. func transitionToViewController(atIndex index: Int) {
  183. selectedIndex = index
  184. }
  185. }
  186. // MARK: - Foundation Extensions
  187. extension Date {
  188. var description: String {
  189. let dateFormatter = DateFormatter()
  190. dateFormatter.dateStyle = .medium
  191. dateFormatter.timeStyle = .short
  192. return dateFormatter.string(from: self)
  193. }
  194. }