Extensions.swift 8.0 KB

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