Extensions.swift 7.9 KB

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