Extension.swift 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. //
  2. // StringUtil.swift
  3. // Runner
  4. //
  5. // Created by Yayan Dwi on 20/04/20.
  6. // Copyright © 2020 The Chromium Authors. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. import SDWebImage
  11. extension Date {
  12. public func currentTimeMillis() -> Int {
  13. return Int(self.timeIntervalSince1970 * 1000)
  14. }
  15. func format(dateFormat: String) -> String {
  16. let formatter = DateFormatter()
  17. formatter.dateFormat = dateFormat
  18. return formatter.string(from: self)
  19. }
  20. var millisecondsSince1970:Int64 {
  21. return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
  22. }
  23. public init(milliseconds:Int64) {
  24. self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
  25. }
  26. }
  27. extension String {
  28. func toNormalString() -> String {
  29. let _source = self.replacingOccurrences(of: "+", with: "%20")
  30. if var result = _source.removingPercentEncoding {
  31. result = result.replacingOccurrences(of: "<NL>", with: "\n")
  32. result = result.replacingOccurrences(of: "<CR>", with: "\r")
  33. return decrypt(source: result)
  34. }
  35. return self
  36. }
  37. func toStupidString() -> String {
  38. if var result = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  39. result = result.replacingOccurrences(of: "\n", with: "<NL>")
  40. result = result.replacingOccurrences(of: "\r", with: "<CR>")
  41. result = result.replacingOccurrences(of: "+", with: "%2B")
  42. return result
  43. }
  44. return self
  45. }
  46. private func decrypt(source : String) -> String {
  47. if let result = source.removingPercentEncoding {
  48. return result
  49. }
  50. return source
  51. }
  52. public func matches(_ regex: String) -> Bool {
  53. return self.range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil
  54. }
  55. }
  56. extension Int {
  57. func toHex() -> String {
  58. return String(format: "%02X", self)
  59. }
  60. }
  61. extension UIApplication {
  62. public static var appVersion: String? {
  63. return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
  64. }
  65. var rootViewController: UIViewController? {
  66. return UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
  67. }
  68. public var visibleViewController: UIViewController? {
  69. let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
  70. if var topController = keyWindow?.rootViewController {
  71. while let presentedViewController = topController.presentedViewController {
  72. topController = presentedViewController
  73. }
  74. return topController
  75. }
  76. return nil
  77. }
  78. }
  79. extension UIView {
  80. public func anchor(top: NSLayoutYAxisAnchor? = nil,
  81. left: NSLayoutXAxisAnchor? = nil,
  82. bottom: NSLayoutYAxisAnchor? = nil,
  83. right: NSLayoutXAxisAnchor? = nil,
  84. paddingTop: CGFloat = 0,
  85. paddingLeft: CGFloat = 0,
  86. paddingBottom: CGFloat = 0,
  87. paddingRight: CGFloat = 0,
  88. centerX: NSLayoutXAxisAnchor? = nil,
  89. centerY: NSLayoutYAxisAnchor? = nil,
  90. width: CGFloat = 0,
  91. height: CGFloat = 0,
  92. minHeight: CGFloat = 0,
  93. maxHeight: CGFloat = 0,
  94. minWidth: CGFloat = 0,
  95. maxWidth: CGFloat = 0,
  96. dynamicLeft: Bool = false,
  97. dynamicRight: Bool = false) {
  98. translatesAutoresizingMaskIntoConstraints = false
  99. if let top = top {
  100. topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
  101. }
  102. if let left = left {
  103. if dynamicLeft {
  104. leftAnchor.constraint(greaterThanOrEqualTo: left, constant: paddingLeft).isActive = true
  105. } else {
  106. leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
  107. }
  108. }
  109. if let right = right {
  110. if dynamicRight {
  111. leftAnchor.constraint(lessThanOrEqualTo: right, constant: -paddingRight).isActive = true
  112. } else {
  113. rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
  114. }
  115. }
  116. if let bottom = bottom {
  117. bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
  118. }
  119. if let centerX = centerX {
  120. centerXAnchor.constraint(equalTo: centerX).isActive = true
  121. }
  122. if let centerY = centerY {
  123. centerYAnchor.constraint(equalTo: centerY).isActive = true
  124. }
  125. if height != 0 || minHeight != 0 || maxHeight != 0 {
  126. if minHeight != 0 && maxHeight != 0 {
  127. heightAnchor.constraint(greaterThanOrEqualToConstant: minHeight).isActive = true
  128. heightAnchor.constraint(lessThanOrEqualToConstant: maxHeight).isActive = true
  129. } else if minHeight != 0 && maxHeight == 0 {
  130. heightAnchor.constraint(greaterThanOrEqualToConstant: minHeight).isActive = true
  131. } else if minHeight == 0 && maxHeight != 0 {
  132. heightAnchor.constraint(lessThanOrEqualToConstant: maxHeight).isActive = true
  133. } else {
  134. heightAnchor.constraint(equalToConstant: height).isActive = true
  135. }
  136. }
  137. if width != 0 || minWidth != 0 || maxWidth != 0 {
  138. if minWidth != 0 && maxWidth != 0 {
  139. heightAnchor.constraint(greaterThanOrEqualToConstant: minWidth).isActive = true
  140. heightAnchor.constraint(lessThanOrEqualToConstant: maxWidth).isActive = true
  141. } else if minWidth != 0 && maxWidth == 0 {
  142. heightAnchor.constraint(greaterThanOrEqualToConstant: minWidth).isActive = true
  143. } else if minWidth == 0 && maxWidth != 0 {
  144. heightAnchor.constraint(lessThanOrEqualToConstant: maxWidth).isActive = true
  145. } else {
  146. widthAnchor.constraint(equalToConstant: width).isActive = true
  147. }
  148. }
  149. }
  150. public func addTopBorder(with color: UIColor?, andWidth borderWidth: CGFloat, view: UIView = UIView()) {
  151. let border = view
  152. border.backgroundColor = color
  153. border.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
  154. border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: borderWidth)
  155. addSubview(border)
  156. }
  157. public func addBottomBorder(with color: UIColor?, andWidth borderWidth: CGFloat, x: CGFloat = 0, view: UIView = UIView()) {
  158. let border = view
  159. border.backgroundColor = color
  160. border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
  161. border.frame = CGRect(x: x, y: frame.size.height - borderWidth, width: frame.size.width, height: borderWidth)
  162. addSubview(border)
  163. }
  164. public func addLeftBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
  165. let border = UIView()
  166. border.backgroundColor = color
  167. border.frame = CGRect(x: 0, y: 0, width: borderWidth, height: frame.size.height)
  168. border.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
  169. addSubview(border)
  170. }
  171. public func addRightBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
  172. let border = UIView()
  173. border.backgroundColor = color
  174. border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
  175. border.frame = CGRect(x: frame.size.width - borderWidth, y: 0, width: borderWidth, height: frame.size.height)
  176. addSubview(border)
  177. }
  178. }
  179. extension UIViewController {
  180. var previousViewController: UIViewController? {
  181. guard let navigationController = navigationController else { return nil }
  182. let count = navigationController.viewControllers.count
  183. return count < 2 ? nil : navigationController.viewControllers[count - 2]
  184. }
  185. }
  186. extension UIImage {
  187. func resize(target: CGSize) -> UIImage {
  188. // Determine the scale factor that preserves aspect ratio
  189. let widthRatio = target.width / size.width
  190. let heightRatio = target.height / size.height
  191. let scaleFactor = min(widthRatio, heightRatio)
  192. // Compute the new image size that preserves aspect ratio
  193. let scaledImageSize = CGSize(
  194. width: size.width * scaleFactor,
  195. height: size.height * scaleFactor
  196. )
  197. // Draw and return the resized UIImage
  198. let renderer = UIGraphicsImageRenderer(
  199. size: scaledImageSize
  200. )
  201. let scaledImage = renderer.image { _ in
  202. self.draw(in: CGRect(
  203. origin: .zero,
  204. size: scaledImageSize
  205. ))
  206. }
  207. return scaledImage
  208. }
  209. }
  210. extension UIImage {
  211. var isPortrait: Bool { size.height > size.width }
  212. var isLandscape: Bool { size.width > size.height }
  213. var breadth: CGFloat { min(size.width, size.height) }
  214. var breadthSize: CGSize { .init(width: breadth, height: breadth) }
  215. var breadthRect: CGRect { .init(origin: .zero, size: breadthSize) }
  216. public var circleMasked: UIImage? {
  217. guard let cgImage = cgImage?
  218. .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
  219. y: isPortrait ? ((size.height-size.width)/2).rounded(.down) : 0),
  220. size: breadthSize)) else { return nil }
  221. let format = imageRendererFormat
  222. format.opaque = false
  223. return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
  224. UIBezierPath(ovalIn: breadthRect).addClip()
  225. UIImage(cgImage: cgImage, scale: format.scale, orientation: imageOrientation)
  226. .draw(in: .init(origin: .zero, size: breadthSize))
  227. }
  228. }
  229. }
  230. extension NSObject {
  231. private static var urlStore = [String:String]()
  232. public func getImage(name url: String, placeholderImage: UIImage? = nil, isCircle: Bool = false, tableView: UITableView? = nil, indexPath: IndexPath? = nil, completion: @escaping (Bool, Bool, UIImage?)->()) {
  233. let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
  234. type(of: self).urlStore[tmpAddress] = url
  235. if url.isEmpty {
  236. completion(false, false, placeholderImage)
  237. return
  238. }
  239. do {
  240. let documentDir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
  241. let file = documentDir.appendingPathComponent(url)
  242. if FileManager().fileExists(atPath: file.path) {
  243. let image = UIImage(contentsOfFile: file.path)?.sd_resizedImage(with: CGSize(width: 400, height: 400), scaleMode: .aspectFill)
  244. completion(true, false, isCircle ? image?.circleMasked : image)
  245. } else {
  246. completion(false, false, placeholderImage)
  247. Download().startHTTP(forKey: url) { (name, progress) in
  248. guard progress == 100 else {
  249. return
  250. }
  251. DispatchQueue.main.async {
  252. if tableView != nil {
  253. tableView!.beginUpdates()
  254. tableView!.reloadRows(at: [indexPath!], with: .none)
  255. tableView!.endUpdates()
  256. }
  257. if type(of: self).urlStore[tmpAddress] == name {
  258. let image = UIImage(contentsOfFile: file.path)?.sd_resizedImage(with: CGSize(width: 400, height: 400), scaleMode: .aspectFill)
  259. completion(true, true, isCircle ? image?.circleMasked : image)
  260. }
  261. }
  262. }
  263. }
  264. } catch {}
  265. }
  266. func loadImage(named: String, placeholderImage: UIImage?, completion: @escaping (UIImage?, Bool) -> ()) {
  267. guard !named.isEmpty else {
  268. completion(placeholderImage, true)
  269. return
  270. }
  271. SDWebImageManager.shared.loadImage(with: URL.palioImage(named: named), options: .highPriority, progress: .none) { image, data, error, type, finish, url in
  272. completion(image, finish)
  273. }
  274. }
  275. public func deleteAllRecordDatabase() {
  276. Database.shared.database?.inTransaction({ fmdb, rollback in
  277. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "BUDDY", _where: "")
  278. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "GROUPZ", _where: "")
  279. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE", _where: "")
  280. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "GROUPZ_MEMBER", _where: "")
  281. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "DISCUSSION_FORUM", _where: "")
  282. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "POST", _where: "")
  283. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_STATUS", _where: "")
  284. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_SUMMARY", _where: "")
  285. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "OUTGOING", _where: "")
  286. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "FOLLOW", _where: "")
  287. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "MESSAGE_FAVORITE", _where: "")
  288. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "LINK_PREVIEW", _where: "")
  289. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "PULL_DB", _where: "")
  290. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "PREFS", _where: "")
  291. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "CALL_CENTER_HISTORY", _where: "")
  292. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "FORM_DATA", _where: "")
  293. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "TASK_PIC", _where: "")
  294. _ = Database.shared.deleteRecord(fmdb: fmdb, table: "TASK_DETAIL", _where: "")
  295. })
  296. }
  297. }
  298. extension URL {
  299. static func palioImage(named: String) -> URL? {
  300. return URL(string: "https://newuniverse.io/filepalio/image/\(named)")
  301. }
  302. }
  303. extension UIColor {
  304. public static var mainColor: UIColor {
  305. renderColor(hex: "#d41f26")
  306. }
  307. public static var secondaryColor: UIColor {
  308. return renderColor(hex: "#FAFAFF")
  309. }
  310. public static var orangeColor: UIColor {
  311. return renderColor(hex: "#FFA03E")
  312. }
  313. public static var orangeBNI: UIColor {
  314. return renderColor(hex: "#EE6600")
  315. }
  316. public static var greenColor: UIColor {
  317. return renderColor(hex: "#C7EA46")
  318. }
  319. public static var grayColor: UIColor {
  320. return renderColor(hex: "#F5F5F5")
  321. }
  322. public static var docColor: UIColor {
  323. return renderColor(hex: "#798F9A")
  324. }
  325. public static var mentionColor: UIColor {
  326. return renderColor(hex: "#53bdea")
  327. }
  328. public static var blueBubbleColor: UIColor {
  329. return renderColor(hex: "#C5D1E1")
  330. }
  331. public static var officialColor: UIColor {
  332. return renderColor(hex: "#4c87ef")
  333. }
  334. public static var verifiedColor: UIColor {
  335. return renderColor(hex: "#00b333")
  336. }
  337. public static var ccColor: UIColor {
  338. return renderColor(hex: "#FFF1A353")
  339. }
  340. public static var internalColor: UIColor {
  341. return renderColor(hex: "#ff0000")
  342. }
  343. public class func renderColor(hex: String) -> UIColor {
  344. var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
  345. if (cString.hasPrefix("#")) {
  346. cString.remove(at: cString.startIndex)
  347. }
  348. if ((cString.count) != 6) {
  349. return UIColor.gray
  350. }
  351. var rgbValue:UInt64 = 0
  352. Scanner(string: cString).scanHexInt64(&rgbValue)
  353. return UIColor(
  354. red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
  355. green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
  356. blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
  357. alpha: CGFloat(1.0)
  358. )
  359. }
  360. }
  361. extension UIView {
  362. public func circle() {
  363. layer.cornerRadius = 0.5 * bounds.size.width
  364. clipsToBounds = true
  365. }
  366. public func maxCornerRadius() -> CGFloat {
  367. return (self.frame.width > self.frame.height) ? self.frame.height / 2 : self.frame.width / 2
  368. }
  369. }
  370. extension String {
  371. public func localized(uppercased: Bool = false) -> String {
  372. if let _ = UserDefaults.standard.string(forKey: "i18n_language") {} else {
  373. // we set a default, just in case
  374. let langDefault = UserDefaults.standard.stringArray(forKey: "AppleLanguages")
  375. if langDefault![0].contains("id") {
  376. UserDefaults.standard.set("id", forKey: "i18n_language")
  377. UserDefaults.standard.synchronize()
  378. } else {
  379. UserDefaults.standard.set("en", forKey: "i18n_language")
  380. UserDefaults.standard.synchronize()
  381. }
  382. }
  383. let lang = UserDefaults.standard.string(forKey: "i18n_language")
  384. let bundle = Bundle.resourceBundle(for: DigiX.self).path(forResource: lang, ofType: "lproj")
  385. let bundlePath = Bundle(path: bundle!)
  386. let result = NSLocalizedString(
  387. self,
  388. tableName: "Localizable",
  389. bundle: bundlePath!,
  390. value: self,
  391. comment: self)
  392. if uppercased {
  393. return result.uppercased()
  394. }
  395. return result
  396. }
  397. }
  398. extension UIViewController {
  399. public func showToast(message : String, font: UIFont = UIFont.systemFont(ofSize: 12, weight: .medium), controller: UIViewController) {
  400. let toastContainer = UIView(frame: CGRect())
  401. toastContainer.backgroundColor = UIColor.mainColor.withAlphaComponent(0.6)
  402. toastContainer.alpha = 0.0
  403. toastContainer.layer.cornerRadius = 25;
  404. toastContainer.clipsToBounds = true
  405. let toastLabel = UILabel(frame: CGRect())
  406. toastLabel.textColor = UIColor.white
  407. toastLabel.textAlignment = .center;
  408. toastLabel.font = font
  409. toastLabel.text = message
  410. toastLabel.clipsToBounds = true
  411. toastLabel.numberOfLines = 0
  412. toastContainer.addSubview(toastLabel)
  413. controller.view.addSubview(toastContainer)
  414. controller.view.bringSubviewToFront(toastContainer)
  415. toastLabel.translatesAutoresizingMaskIntoConstraints = false
  416. toastContainer.translatesAutoresizingMaskIntoConstraints = false
  417. let a1 = NSLayoutConstraint(item: toastLabel, attribute: .leading, relatedBy: .equal, toItem: toastContainer, attribute: .leading, multiplier: 1, constant: 15)
  418. let a2 = NSLayoutConstraint(item: toastLabel, attribute: .trailing, relatedBy: .equal, toItem: toastContainer, attribute: .trailing, multiplier: 1, constant: -15)
  419. let a3 = NSLayoutConstraint(item: toastLabel, attribute: .bottom, relatedBy: .equal, toItem: toastContainer, attribute: .bottom, multiplier: 1, constant: -15)
  420. let a4 = NSLayoutConstraint(item: toastLabel, attribute: .top, relatedBy: .equal, toItem: toastContainer, attribute: .top, multiplier: 1, constant: 15)
  421. toastContainer.addConstraints([a1, a2, a3, a4])
  422. let c1 = NSLayoutConstraint(item: toastContainer, attribute: .leading, relatedBy: .equal, toItem: controller.view, attribute: .leading, multiplier: 1, constant: 65)
  423. let c2 = NSLayoutConstraint(item: toastContainer, attribute: .trailing, relatedBy: .equal, toItem: controller.view, attribute: .trailing, multiplier: 1, constant: -65)
  424. let c3 = NSLayoutConstraint(item: toastContainer, attribute: .bottom, relatedBy: .equal, toItem: controller.view, attribute: .bottom, multiplier: 1, constant: -75)
  425. controller.view.addConstraints([c1, c2, c3])
  426. UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseIn, animations: {
  427. toastContainer.alpha = 1.0
  428. }, completion: { _ in
  429. UIView.animate(withDuration: 0.5, delay: 1.5, options: .curveEaseOut, animations: {
  430. toastContainer.alpha = 0.0
  431. }, completion: {_ in
  432. toastContainer.removeFromSuperview()
  433. })
  434. })
  435. }
  436. public func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
  437. UIGraphicsBeginImageContextWithOptions(targetSize, false, 0.0);
  438. image.draw(in: CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height))
  439. let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
  440. UIGraphicsEndImageContext()
  441. return newImage
  442. }
  443. }
  444. extension UITextView {
  445. enum ShouldChangeCursor {
  446. case incrementCursor
  447. case preserveCursor
  448. }
  449. func preserveCursorPosition(withChanges mutatingFunction: (UITextPosition?) -> (ShouldChangeCursor)) {
  450. //save the cursor positon
  451. var cursorPosition: UITextPosition? = nil
  452. if let selectedRange = self.selectedTextRange {
  453. let offset = self.offset(from: self.beginningOfDocument, to: selectedRange.start)
  454. cursorPosition = self.position(from: self.beginningOfDocument, offset: offset)
  455. }
  456. //make mutaing changes that may reset the cursor position
  457. let shouldChangeCursor = mutatingFunction(cursorPosition)
  458. //restore the cursor
  459. if var cursorPosition = cursorPosition {
  460. if shouldChangeCursor == .incrementCursor {
  461. cursorPosition = self.position(from: cursorPosition, offset: 1) ?? cursorPosition
  462. }
  463. if let range = self.textRange(from: cursorPosition, to: cursorPosition) {
  464. self.selectedTextRange = range
  465. }
  466. }
  467. }
  468. }
  469. extension String {
  470. public func substring(from: Int?, to: Int?) -> String {
  471. if let start = from {
  472. guard start < self.count else {
  473. return ""
  474. }
  475. }
  476. if let end = to {
  477. guard end >= 0 else {
  478. return ""
  479. }
  480. }
  481. if let start = from, let end = to {
  482. guard end - start >= 0 else {
  483. return ""
  484. }
  485. }
  486. let startIndex: String.Index
  487. if let start = from, start >= 0 {
  488. startIndex = self.index(self.startIndex, offsetBy: start)
  489. } else {
  490. startIndex = self.startIndex
  491. }
  492. let endIndex: String.Index
  493. if let end = to, end >= 0, end < self.count {
  494. endIndex = self.index(self.startIndex, offsetBy: end + 1)
  495. } else {
  496. endIndex = self.endIndex
  497. }
  498. return String(self[startIndex ..< endIndex])
  499. }
  500. func countEmojiCharacter() -> Int {
  501. func isEmoji(s:NSString) -> Bool {
  502. let high:Int = Int(s.character(at: 0))
  503. if 0xD800 <= high && high <= 0xDBFF {
  504. let low:Int = Int(s.character(at: 1))
  505. let codepoint: Int = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000
  506. return (0x1D000 <= codepoint && codepoint <= 0x1F9FF)
  507. }
  508. else {
  509. return (0x2100 <= high && high <= 0x27BF)
  510. }
  511. }
  512. let nsString = self as NSString
  513. var length = 0
  514. nsString.enumerateSubstrings(in: NSMakeRange(0, nsString.length), options: NSString.EnumerationOptions.byComposedCharacterSequences) { (subString, substringRange, enclosingRange, stop) -> Void in
  515. if isEmoji(s: subString! as NSString) {
  516. length+=1
  517. }
  518. }
  519. return length
  520. }
  521. public func richText(isEditing: Bool = false, isSearching: Bool = false, textSearch: String = "", group_id: String = "", listMentionInTextField: [User] = []) -> NSMutableAttributedString {
  522. let font = UIFont.systemFont(ofSize: 12)
  523. let textUTF8 = String(self.utf8)
  524. let finalText = NSMutableAttributedString(string: textUTF8, attributes: [NSAttributedString.Key.font: font])
  525. let boldSign: Character = "*"
  526. let italicSign: Character = "_"
  527. let underlineSign: Character = "^"
  528. let strikethroughSign: Character = "~"
  529. //Bold
  530. let rangeBold = getRangeOfWordWithSign(sentence: textUTF8, sign: boldSign)
  531. if rangeBold.count > 0 {
  532. var lastFirstRange = -1
  533. var countRemoveBoldSign = 0
  534. var continueCheckingBold = false
  535. var totalEmoji = 0
  536. for i in 0..<rangeBold.count {
  537. if lastFirstRange == -1 {
  538. if (rangeBold[i].startIndex == 0 || checkCharBefore(char: textUTF8.substring(from: rangeBold[i].startIndex - 1, to: rangeBold[i].startIndex - 1))) {
  539. lastFirstRange = rangeBold[i].startIndex
  540. continueCheckingBold = true
  541. } else {
  542. continueCheckingBold = false
  543. }
  544. }
  545. if !continueCheckingBold {
  546. continue
  547. }
  548. if rangeBold[i].endIndex != (textUTF8.count-1) {
  549. let char: Character = Array(textUTF8.substring(from: rangeBold[i].endIndex + 1, to: rangeBold[i].endIndex + 1))[0]
  550. if char.isLetter || char.isNumber {
  551. continue
  552. }
  553. }
  554. let countEmojiBefore = finalText.string.substring(from: 0, to: lastFirstRange - (2*countRemoveBoldSign)).countEmojiCharacter()
  555. let countEmoji = finalText.string.substring(from: lastFirstRange - (2*countRemoveBoldSign), to: rangeBold[i].endIndex - (2*countRemoveBoldSign)).countEmojiCharacter()
  556. totalEmoji = countEmoji + countEmojiBefore
  557. finalText.addAttribute(.font, value: font.bold, range: NSRange(location: lastFirstRange - (2*countRemoveBoldSign) + countEmojiBefore, length: (rangeBold[i].endIndex + countEmoji + 1) - lastFirstRange))
  558. if !isEditing{
  559. finalText.mutableString.replaceOccurrences(of: "\(boldSign)", with: "", options: .literal, range: NSRange(location: lastFirstRange + countEmojiBefore - (2*countRemoveBoldSign), length: 1))
  560. finalText.mutableString.replaceOccurrences(of: "\(boldSign)", with: "", options: .literal, range: NSRange(location: rangeBold[i].endIndex + totalEmoji - (2*countRemoveBoldSign) - 1, length: 1))
  561. countRemoveBoldSign += 1
  562. } else {
  563. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: lastFirstRange + countEmojiBefore, length: 1))
  564. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: rangeBold[i].endIndex + totalEmoji, length: 1))
  565. }
  566. lastFirstRange = -1
  567. }
  568. }
  569. //Italic
  570. let textAfterbold = finalText.string
  571. let rangeItalic = getRangeOfWordWithSign(sentence: textAfterbold, sign: italicSign)
  572. if rangeItalic.count > 0 {
  573. var lastFirstRange = -1
  574. var countRemoveItalicSign = 0
  575. var continueCheckingItalic = false
  576. var totalEmoji = 0
  577. for i in 0..<rangeItalic.count {
  578. if lastFirstRange == -1 {
  579. if (rangeItalic[i].startIndex == 0 || checkCharBefore(char: textAfterbold.substring(from: rangeItalic[i].startIndex - 1, to: rangeItalic[i].startIndex - 1))) {
  580. lastFirstRange = rangeItalic[i].startIndex
  581. continueCheckingItalic = true
  582. } else {
  583. continueCheckingItalic = false
  584. }
  585. }
  586. if !continueCheckingItalic {
  587. continue
  588. }
  589. if rangeItalic[i].endIndex != (textUTF8.count-1) {
  590. let char: Character = Array(textUTF8.substring(from: rangeItalic[i].endIndex + 1, to: rangeItalic[i].endIndex + 1))[0]
  591. if char.isLetter || char.isNumber {
  592. continue
  593. }
  594. }
  595. let countEmojiBefore = finalText.string.substring(from: 0, to: lastFirstRange - (2*countRemoveItalicSign)).countEmojiCharacter()
  596. let countEmoji = finalText.string.substring(from: lastFirstRange - (2*countRemoveItalicSign), to: rangeItalic[i].endIndex - (2*countRemoveItalicSign)).countEmojiCharacter()
  597. totalEmoji = countEmoji + countEmojiBefore
  598. finalText.addAttribute(.font, value: font.italic, range: NSRange(location: lastFirstRange - (2*countRemoveItalicSign) + countEmojiBefore, length: (rangeItalic[i].endIndex + countEmoji + 1) - lastFirstRange))
  599. if !isEditing{
  600. finalText.mutableString.replaceOccurrences(of: "\(italicSign)", with: "", options: .literal, range: NSRange(location: lastFirstRange + countEmojiBefore - (2*countRemoveItalicSign), length: 1))
  601. finalText.mutableString.replaceOccurrences(of: "\(italicSign)", with: "", options: .literal, range: NSRange(location: rangeItalic[i].endIndex + totalEmoji - (2*countRemoveItalicSign) - 1, length: 1))
  602. countRemoveItalicSign += 1
  603. } else {
  604. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: lastFirstRange + countEmojiBefore, length: 1))
  605. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: rangeItalic[i].endIndex + totalEmoji, length: 1))
  606. }
  607. lastFirstRange = -1
  608. }
  609. }
  610. //Underline
  611. let textAfterItalic = finalText.string
  612. let rangeUnderline = getRangeOfWordWithSign(sentence: textAfterItalic, sign: underlineSign)
  613. if rangeUnderline.count > 0 {
  614. var lastFirstRange = -1
  615. var countRemoveUnderlineSign = 0
  616. var continueCheckingUnderline = false
  617. var totalEmoji = 0
  618. for i in 0..<rangeUnderline.count {
  619. if lastFirstRange == -1 {
  620. if (rangeUnderline[i].startIndex == 0 || checkCharBefore(char: textAfterItalic.substring(from: rangeUnderline[i].startIndex - 1, to: rangeUnderline[i].startIndex - 1))) {
  621. lastFirstRange = rangeUnderline[i].startIndex
  622. continueCheckingUnderline = true
  623. } else {
  624. continueCheckingUnderline = false
  625. }
  626. }
  627. if !continueCheckingUnderline {
  628. continue
  629. }
  630. if rangeUnderline[i].endIndex != (textUTF8.count-1) {
  631. let char: Character = Array(textUTF8.substring(from: rangeUnderline[i].endIndex + 1, to: rangeUnderline[i].endIndex + 1))[0]
  632. if char.isLetter || char.isNumber {
  633. continue
  634. }
  635. }
  636. let countEmojiBefore = finalText.string.substring(from: 0, to: lastFirstRange - (2*countRemoveUnderlineSign)).countEmojiCharacter()
  637. let countEmoji = finalText.string.substring(from: lastFirstRange - (2*countRemoveUnderlineSign), to: rangeUnderline[i].endIndex - (2*countRemoveUnderlineSign)).countEmojiCharacter()
  638. totalEmoji = countEmoji + countEmojiBefore
  639. finalText.addAttribute(.underlineStyle, value: NSUnderlineStyle.thick.rawValue, range: NSRange(location: lastFirstRange - (2*countRemoveUnderlineSign) + countEmojiBefore + 1, length: (rangeUnderline[i].endIndex + countEmoji - 1) - lastFirstRange))
  640. if !isEditing{
  641. finalText.mutableString.replaceOccurrences(of: "\(underlineSign)", with: "", options: .literal, range: NSRange(location: lastFirstRange + countEmojiBefore - (2*countRemoveUnderlineSign), length: 1))
  642. finalText.mutableString.replaceOccurrences(of: "\(underlineSign)", with: "", options: .literal, range: NSRange(location: rangeUnderline[i].endIndex + totalEmoji - (2*countRemoveUnderlineSign) - 1, length: 1))
  643. countRemoveUnderlineSign += 1
  644. } else {
  645. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: lastFirstRange + countEmojiBefore, length: 1))
  646. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: rangeUnderline[i].endIndex + totalEmoji, length: 1))
  647. }
  648. lastFirstRange = -1
  649. }
  650. }
  651. //Strikethrough
  652. let textAfterUnderline = finalText.string
  653. let rangeStrikethrough = getRangeOfWordWithSign(sentence: textAfterUnderline, sign: strikethroughSign)
  654. if rangeStrikethrough.count > 0 {
  655. var lastFirstRange = -1
  656. var countRemoveStrikethroughSign = 0
  657. var continueCheckingStrikethrough = false
  658. var totalEmoji = 0
  659. for i in 0..<rangeStrikethrough.count {
  660. if lastFirstRange == -1 {
  661. if (rangeStrikethrough[i].startIndex == 0 || checkCharBefore(char: textAfterUnderline.substring(from: rangeStrikethrough[i].startIndex - 1, to: rangeStrikethrough[i].startIndex - 1))) {
  662. lastFirstRange = rangeStrikethrough[i].startIndex
  663. continueCheckingStrikethrough = true
  664. } else {
  665. continueCheckingStrikethrough = false
  666. }
  667. }
  668. if !continueCheckingStrikethrough {
  669. continue
  670. }
  671. if rangeStrikethrough[i].endIndex != (textUTF8.count-1) {
  672. let char: Character = Array(textUTF8.substring(from: rangeStrikethrough[i].endIndex + 1, to: rangeStrikethrough[i].endIndex + 1))[0]
  673. if char.isLetter || char.isNumber {
  674. continue
  675. }
  676. }
  677. let countEmojiBefore = finalText.string.substring(from: 0, to: lastFirstRange - (2*countRemoveStrikethroughSign)).countEmojiCharacter()
  678. let countEmoji = finalText.string.substring(from: lastFirstRange - (2*countRemoveStrikethroughSign), to: rangeStrikethrough[i].endIndex - (2*countRemoveStrikethroughSign)).countEmojiCharacter()
  679. totalEmoji = countEmoji + countEmojiBefore
  680. finalText.addAttribute(.strikethroughStyle, value: 2, range: NSRange(location: lastFirstRange - (2*countRemoveStrikethroughSign) + countEmojiBefore + 1, length: (rangeStrikethrough[i].endIndex + countEmoji - 1) - lastFirstRange))
  681. if !isEditing{
  682. finalText.mutableString.replaceOccurrences(of: "\(strikethroughSign)", with: "", options: .literal, range: NSRange(location: lastFirstRange + countEmojiBefore - (2*countRemoveStrikethroughSign), length: 1))
  683. finalText.mutableString.replaceOccurrences(of: "\(strikethroughSign)", with: "", options: .literal, range: NSRange(location: rangeStrikethrough[i].endIndex + totalEmoji - (2*countRemoveStrikethroughSign) - 1, length: 1))
  684. countRemoveStrikethroughSign += 1
  685. } else {
  686. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: lastFirstRange + countEmojiBefore, length: 1))
  687. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: rangeStrikethrough[i].endIndex + totalEmoji, length: 1))
  688. }
  689. lastFirstRange = -1
  690. }
  691. }
  692. //Check Mention
  693. let finalTextAfterRichText = finalText.string
  694. if finalTextAfterRichText.contains("@") {
  695. if !group_id.isEmpty {
  696. let listMembers = Member.getAllMember(group_id: group_id)
  697. if listMembers.count > 0 {
  698. for i in 0..<listMembers.count {
  699. if isEditing {
  700. if listMentionInTextField.count > 0 {
  701. let name = (listMembers[i].firstName + " " + listMembers[i].lastName).trimmingCharacters(in: .whitespaces)
  702. if listMentionInTextField.firstIndex(where: { ($0.firstName + " " + $0.lastName).trimmingCharacters(in: .whitespaces) == name }) != nil {
  703. let range = NSString(string: finalTextAfterRichText).range(of: "@\(name)", options: .caseInsensitive)
  704. finalText.addAttribute(.foregroundColor, value: UIColor.mentionColor, range: range)
  705. }
  706. }
  707. } else {
  708. let name = (listMembers[i].firstName + " " + listMembers[i].lastName).trimmingCharacters(in: .whitespaces)
  709. let range = NSString(string: finalTextAfterRichText).range(of: listMembers[i].pin, options: .caseInsensitive)
  710. if range.lowerBound != range.upperBound {
  711. finalText.mutableString.replaceOccurrences(of: listMembers[i].pin, with: name, options: .literal, range: range)
  712. finalText.addAttribute(.foregroundColor, value: UIColor.mentionColor, range: NSString(string: finalText.string).range(of: "@\(name)"))
  713. }
  714. }
  715. }
  716. }
  717. } else {
  718. let listTextEnter = finalText.string.split(separator: "\n")
  719. for j in 0...listTextEnter.count - 1 {
  720. let listText = listTextEnter[j].split(separator: " ")
  721. let listMention = listText.filter({ $0.starts(with: "@")})
  722. if listMention.count > 0 {
  723. for i in 0..<listMention.count {
  724. let f_pin = (String(listMention[i])).substring(from: 1, to: listMention[i].count)
  725. let member = Member.getMember(f_pin: f_pin)
  726. if member != nil {
  727. let name = (member!.firstName + " " + member!.lastName).trimmingCharacters(in: .whitespaces)
  728. finalText.mutableString.replaceOccurrences(of: f_pin, with: name, options: .literal, range: NSString(string: finalText.string).range(of: f_pin))
  729. }
  730. }
  731. }
  732. }
  733. }
  734. }
  735. if isSearching {
  736. let range = NSString(string: finalText.string).range(of: textSearch, options: .caseInsensitive) // 2
  737. let highlightColor = UIColor.systemYellow // 3
  738. let highlightedAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.backgroundColor: highlightColor] // 4
  739. finalText.addAttributes(highlightedAttributes, range: range) // 5
  740. }
  741. return finalText
  742. }
  743. func checkCharBefore(char: String) -> Bool {
  744. return char == " " || char == "\n"
  745. }
  746. func checkStartWithLink() -> Bool {
  747. return self.starts(with: "https://") || self.starts(with: "http://") || self.starts(with: "www.")
  748. //|| self.starts(with: "*https://") || self.starts(with: "*http://") || self.starts(with: "*www.") || self.starts(with: "_https://") || self.starts(with: "_http://") || self.starts(with: "_www.") || self.starts(with: "^https://") || self.starts(with: "^http://") || self.starts(with: "^www.") || self.starts(with: "~https://") || self.starts(with: "~http://") || self.starts(with: "~www.")
  749. }
  750. func getRangeOfWordWithSign(sentence: String, sign: Character) -> [Range<Int>] {
  751. let asterisk: Character = sign
  752. var ranges = [Range<Int>]()
  753. var startIndex = sentence.startIndex
  754. while let startRange = sentence[startIndex...].firstIndex(of: asterisk),
  755. let endRange = sentence[startRange...].dropFirst().firstIndex(of: asterisk) {
  756. let range = startRange..<endRange
  757. let word = sentence[range].replacingOccurrences(of: "\(sign)", with: "")
  758. if !word.isEmpty {
  759. let lower = sentence.distance(from: sentence.startIndex, to: startRange)
  760. let upper = sentence.distance(from: sentence.startIndex, to: endRange)
  761. ranges.append(Range(uncheckedBounds: (lower: lower, upper: upper)))
  762. }
  763. startIndex = endRange
  764. }
  765. return ranges
  766. }
  767. }
  768. extension UIFont {
  769. var bold: UIFont {
  770. return with(traits: .traitBold)
  771. } // bold
  772. var italic: UIFont {
  773. return with(traits: .traitItalic)
  774. } // italic
  775. func with(traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
  776. guard let descriptor = self.fontDescriptor.withSymbolicTraits(traits) else {
  777. return self
  778. } // guard
  779. return UIFont(descriptor: descriptor, size: 0)
  780. } // with(traits:)
  781. }
  782. extension UILabel {
  783. public func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat) {
  784. let attachment = NSTextAttachment()
  785. attachment.image = image
  786. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  787. let attachmentStr = NSAttributedString(attachment: attachment)
  788. let mutableAttributedString = NSMutableAttributedString()
  789. mutableAttributedString.append(attachmentStr)
  790. let textString = NSAttributedString(string: text, attributes: [.font: self.font!])
  791. mutableAttributedString.append(textString)
  792. self.attributedText = mutableAttributedString
  793. }
  794. public func setAttributeText(image: UIImage, with textMutable: NSAttributedString, size: CGFloat, y: CGFloat) {
  795. let attachment = NSTextAttachment()
  796. attachment.image = image
  797. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  798. let attachmentStr = NSAttributedString(attachment: attachment)
  799. let mutableAttributedString = NSMutableAttributedString()
  800. mutableAttributedString.append(attachmentStr)
  801. mutableAttributedString.append(textMutable)
  802. self.attributedText = mutableAttributedString
  803. }
  804. }
  805. extension Bundle {
  806. public static func resourceBundle(for frameworkClass: AnyClass) -> Bundle {
  807. let frameworkBundle = Bundle(for: frameworkClass)
  808. guard let resourceBundleURL = frameworkBundle.url(forResource: "DigiXLite", withExtension: "bundle"),
  809. let resourceBundle = Bundle(url: resourceBundleURL) else {
  810. return frameworkBundle
  811. }
  812. return resourceBundle
  813. }
  814. public static func resourcesMediaBundle(for frameworkClass: AnyClass) -> Bundle {
  815. let frameworkBundle = Bundle(for: frameworkClass)
  816. guard let resourceBundleURL = frameworkBundle.url(forResource: "DigiXLiteResources", withExtension: "bundle"),
  817. let resourceBundle = Bundle(url: resourceBundleURL) else {
  818. //print(("\(moduleName).bundle not found in \(frameworkBundle)")
  819. return frameworkBundle
  820. }
  821. return resourceBundle
  822. }
  823. }
  824. //extension UIFont {
  825. //
  826. // static func register(from url: URL) throws {
  827. // guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {
  828. // throw fatalError("Could not create font data provider for \(url).")
  829. // }
  830. // let font = CGFont(fontDataProvider)
  831. // var error: Unmanaged<CFError>?
  832. // guard CTFontManagerRegisterGraphicsFont(font!, &error) else {
  833. // throw error!.takeUnretainedValue()
  834. // }
  835. // }
  836. //
  837. //}
  838. extension UIButton {
  839. private func actionHandleBlock(action:(() -> Void)? = nil) {
  840. struct __ {
  841. static var action :(() -> Void)?
  842. }
  843. if action != nil {
  844. __.action = action
  845. } else {
  846. __.action?()
  847. }
  848. }
  849. @objc private func triggerActionHandleBlock() {
  850. self.actionHandleBlock()
  851. }
  852. public func actionHandle(controlEvents control :UIControl.Event, ForAction action:@escaping () -> Void) {
  853. self.actionHandleBlock(action: action)
  854. self.addTarget(self, action: #selector(self.triggerActionHandleBlock), for: control)
  855. }
  856. }
  857. extension UINavigationController {
  858. func replaceAllViewController(with viewController: UIViewController, animated: Bool) {
  859. pushViewController(viewController, animated: animated)
  860. viewControllers.removeSubrange(1...viewControllers.count - 2)
  861. }
  862. var rootViewController : UIViewController? {
  863. return viewControllers.first
  864. }
  865. func popViewController(animated: Bool, completion: @escaping () -> Void) {
  866. popViewController(animated: animated)
  867. if animated, let coordinator = transitionCoordinator {
  868. coordinator.animate(alongsideTransition: nil) { _ in
  869. completion()
  870. }
  871. } else {
  872. completion()
  873. }
  874. }
  875. }
  876. extension UIImageView {
  877. private static var taskKey = 0
  878. private static var urlKey = 0
  879. private var currentTask: URLSessionTask? {
  880. get { return objc_getAssociatedObject(self, &UIImageView.taskKey) as? URLSessionTask }
  881. set { objc_setAssociatedObject(self, &UIImageView.taskKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  882. }
  883. private var currentURL: URL? {
  884. get { return objc_getAssociatedObject(self, &UIImageView.urlKey) as? URL }
  885. set { objc_setAssociatedObject(self, &UIImageView.urlKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  886. }
  887. func loadImageAsync(with urlString: String?) {
  888. // cancel prior task, if any
  889. weak var oldTask = currentTask
  890. currentTask = nil
  891. oldTask?.cancel()
  892. // reset imageview's image
  893. self.image = nil
  894. // allow supplying of `nil` to remove old image and then return immediately
  895. guard let urlString = urlString else { return }
  896. // check cache
  897. if let cachedImage = ImageCache.shared.image(forKey: urlString) {
  898. self.image = cachedImage
  899. return
  900. }
  901. // download
  902. let url = URL(string: urlString)!
  903. currentURL = url
  904. let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
  905. self?.currentTask = nil
  906. //error handling
  907. if let error = error {
  908. // don't bother reporting cancelation errors
  909. if (error as NSError).domain == NSURLErrorDomain && (error as NSError).code == NSURLErrorCancelled {
  910. return
  911. }
  912. //print(error)
  913. return
  914. }
  915. guard let data = data, let downloadedImage = UIImage(data: data) else {
  916. //print(("unable to extract image")
  917. return
  918. }
  919. ImageCache.shared.save(image: downloadedImage, forKey: urlString)
  920. if url == self?.currentURL {
  921. DispatchQueue.main.async {
  922. self?.image = downloadedImage
  923. }
  924. }
  925. }
  926. // save and start new task
  927. currentTask = task
  928. task.resume()
  929. }
  930. private func actionHandleBlock(action:(() -> Void)? = nil) {
  931. struct __ {
  932. static var action :(() -> Void)?
  933. }
  934. if action != nil {
  935. __.action = action
  936. } else {
  937. __.action?()
  938. }
  939. }
  940. @objc private func triggerActionHandleBlock() {
  941. self.actionHandleBlock()
  942. }
  943. func actionHandle(controlEvents control :UIControl.Event, ForAction action:@escaping () -> Void) {
  944. self.actionHandleBlock(action: action)
  945. self.isUserInteractionEnabled = true
  946. self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.triggerActionHandleBlock)))
  947. }
  948. }
  949. extension UITextField {
  950. public enum PaddingSide {
  951. case left(CGFloat)
  952. case right(CGFloat)
  953. case both(CGFloat)
  954. }
  955. public func addPadding(_ padding: PaddingSide) {
  956. self.leftViewMode = .always
  957. self.layer.masksToBounds = true
  958. switch padding {
  959. case .left(let spacing):
  960. let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
  961. self.leftView = paddingView
  962. self.rightViewMode = .always
  963. case .right(let spacing):
  964. let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
  965. self.rightView = paddingView
  966. self.rightViewMode = .always
  967. case .both(let spacing):
  968. let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
  969. // left
  970. self.leftView = paddingView
  971. self.leftViewMode = .always
  972. // right
  973. self.rightView = paddingView
  974. self.rightViewMode = .always
  975. }
  976. }
  977. }
  978. class ImageCache {
  979. private let cache = NSCache<NSString, UIImage>()
  980. private var observer: NSObjectProtocol!
  981. static let shared = ImageCache()
  982. private init() {
  983. // make sure to purge cache on memory pressure
  984. observer = NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: nil) { [weak self] notification in
  985. self?.cache.removeAllObjects()
  986. }
  987. }
  988. deinit {
  989. NotificationCenter.default.removeObserver(observer as Any)
  990. }
  991. func image(forKey key: String) -> UIImage? {
  992. return cache.object(forKey: key as NSString)
  993. }
  994. func save(image: UIImage, forKey key: String) {
  995. cache.setObject(image, forKey: key as NSString)
  996. }
  997. }
  998. public class LibAlertController: UIAlertController {
  999. public override func viewWillAppear(_ animated: Bool) {
  1000. super.viewWillAppear(animated)
  1001. // Customize the title's font
  1002. let titleFont = UIFont.boldSystemFont(ofSize: 16)
  1003. let titleAttributes = [NSAttributedString.Key.font: titleFont]
  1004. setValue(NSAttributedString(string: self.title ?? "", attributes: titleAttributes), forKey: "attributedTitle")
  1005. // Change the font for the message
  1006. let messageFont = UIFont.systemFont(ofSize: 14)
  1007. let messageAttributes = [NSAttributedString.Key.font: messageFont]
  1008. setValue(NSAttributedString(string: self.message ?? "", attributes: messageAttributes), forKey: "attributedMessage")
  1009. for i in self.actions {
  1010. let attributedText = NSAttributedString(string: i.title ?? "", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)])
  1011. guard let label = (i.value(forKey: "__representer") as AnyObject).value(forKey: "label") as? UILabel else { return }
  1012. label.attributedText = attributedText
  1013. }
  1014. }
  1015. }
  1016. extension UISearchBar
  1017. {
  1018. func setMagnifyingGlassColorTo(color: UIColor)
  1019. {
  1020. // Search Icon
  1021. let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
  1022. let glassIconView = textFieldInsideSearchBar?.leftView as? UIImageView
  1023. glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
  1024. glassIconView?.tintColor = color
  1025. }
  1026. func setClearButtonColorTo(color: UIColor)
  1027. {
  1028. // Clear Button
  1029. let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
  1030. let crossIconView = textFieldInsideSearchBar?.value(forKey: "clearButton") as? UIButton
  1031. crossIconView?.setImage(crossIconView?.currentImage?.withRenderingMode(.alwaysTemplate), for: .normal)
  1032. crossIconView?.tintColor = color
  1033. }
  1034. func setPlaceholderTextColorTo(color: UIColor)
  1035. {
  1036. let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
  1037. textFieldInsideSearchBar?.textColor = color
  1038. let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
  1039. textFieldInsideSearchBarLabel?.textColor = color
  1040. }
  1041. }
  1042. extension String {
  1043. init(unicodeScalar: UnicodeScalar) {
  1044. self.init(Character(unicodeScalar))
  1045. }
  1046. init?(unicodeCodepoint: Int) {
  1047. if let unicodeScalar = UnicodeScalar(unicodeCodepoint) {
  1048. self.init(unicodeScalar: unicodeScalar)
  1049. } else {
  1050. return nil
  1051. }
  1052. }
  1053. static func +(lhs: String, rhs: Int) -> String {
  1054. return lhs + String(unicodeCodepoint: rhs)!
  1055. }
  1056. static func +=(lhs: inout String, rhs: Int) {
  1057. lhs = lhs + rhs
  1058. }
  1059. }
  1060. extension UIGraphicsRenderer {
  1061. static func renderImagesAt(urls: [NSURL], size: CGSize, scale: CGFloat = 1) -> UIImage {
  1062. let renderer = UIGraphicsImageRenderer(size: size)
  1063. let options: [NSString: Any] = [
  1064. kCGImageSourceThumbnailMaxPixelSize: max(size.width * scale, size.height * scale),
  1065. kCGImageSourceCreateThumbnailFromImageAlways: true
  1066. ]
  1067. let thumbnails = try urls.map { url -> CGImage in
  1068. let imageSource = CGImageSourceCreateWithURL(url, nil)
  1069. let scaledImage = CGImageSourceCreateThumbnailAtIndex(imageSource!, 0, options as CFDictionary)
  1070. return scaledImage!
  1071. }
  1072. // Translate Y-axis down because cg images are flipped and it falls out of the frame (see bellow)
  1073. let rect = CGRect(x: 0,
  1074. y: -size.height,
  1075. width: size.width,
  1076. height: size.height)
  1077. let resizedImage = renderer.image { ctx in
  1078. let context = ctx.cgContext
  1079. context.scaleBy(x: 1, y: -1) //Flip it ( cg y-axis is flipped)
  1080. for image in thumbnails {
  1081. context.draw(image, in: rect)
  1082. }
  1083. }
  1084. return resizedImage
  1085. }
  1086. static func renderImageAt(url: NSURL, size: CGSize, scale: CGFloat = 1) -> UIImage {
  1087. return renderImagesAt(urls: [url], size: size, scale: scale)
  1088. }
  1089. }