Extensions.swift 8.1 KB

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