Extensions.swift 7.5 KB

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