Extension.swift 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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 = 0
  533. var countRemoveBoldSign = 0
  534. var continueCheckingBold = false
  535. var totalEmoji = 0
  536. for i in 0..<rangeBold.count {
  537. if lastFirstRange == 0 {
  538. if (rangeBold[i].startIndex == 0 || checkCharBeforeAfter(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 || checkCharBeforeAfter(char: textUTF8.substring(from: rangeBold[i].endIndex + 1, to: rangeBold[i].endIndex + 1))) {
  549. let countEmojiBefore = finalText.string.substring(from: 0, to: lastFirstRange - (2*countRemoveBoldSign)).countEmojiCharacter()
  550. let countEmoji = finalText.string.substring(from: lastFirstRange - (2*countRemoveBoldSign), to: rangeBold[i].endIndex - (2*countRemoveBoldSign)).countEmojiCharacter()
  551. totalEmoji = countEmoji + countEmojiBefore
  552. finalText.addAttribute(.font, value: font.bold, range: NSRange(location: lastFirstRange - (2*countRemoveBoldSign) + countEmojiBefore, length: (rangeBold[i].endIndex + countEmoji + 1) - lastFirstRange))
  553. if !isEditing{
  554. finalText.mutableString.replaceOccurrences(of: "\(boldSign)", with: "", options: .literal, range: NSRange(location: lastFirstRange + countEmojiBefore - (2*countRemoveBoldSign), length: 1))
  555. finalText.mutableString.replaceOccurrences(of: "\(boldSign)", with: "", options: .literal, range: NSRange(location: rangeBold[i].endIndex + totalEmoji - (2*countRemoveBoldSign) - 1, length: 1))
  556. countRemoveBoldSign += 1
  557. } else {
  558. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: lastFirstRange + countEmojiBefore, length: 1))
  559. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: rangeBold[i].endIndex + totalEmoji, length: 1))
  560. }
  561. lastFirstRange = 0
  562. }
  563. }
  564. }
  565. //Italic
  566. let textAfterbold = finalText.string
  567. let rangeItalic = getRangeOfWordWithSign(sentence: textAfterbold, sign: italicSign)
  568. if rangeItalic.count > 0 {
  569. var lastFirstRange = 0
  570. var countRemoveItalicSign = 0
  571. var continueCheckingItalic = false
  572. var totalEmoji = 0
  573. for i in 0..<rangeItalic.count {
  574. if lastFirstRange == 0 {
  575. if (rangeItalic[i].startIndex == 0 || checkCharBeforeAfter(char: textAfterbold.substring(from: rangeItalic[i].startIndex - 1, to: rangeItalic[i].startIndex - 1))) {
  576. lastFirstRange = rangeItalic[i].startIndex
  577. continueCheckingItalic = true
  578. } else {
  579. continueCheckingItalic = false
  580. }
  581. }
  582. if !continueCheckingItalic {
  583. continue
  584. }
  585. if (rangeItalic[i].endIndex == textAfterbold.count - 1 || checkCharBeforeAfter(char: textAfterbold.substring(from: rangeItalic[i].endIndex + 1, to: rangeItalic[i].endIndex + 1))) {
  586. let countEmojiBefore = finalText.string.substring(from: 0, to: lastFirstRange - (2*countRemoveItalicSign)).countEmojiCharacter()
  587. let countEmoji = finalText.string.substring(from: lastFirstRange - (2*countRemoveItalicSign), to: rangeItalic[i].endIndex - (2*countRemoveItalicSign)).countEmojiCharacter()
  588. totalEmoji = countEmoji + countEmojiBefore
  589. finalText.addAttribute(.font, value: font.italic, range: NSRange(location: lastFirstRange - (2*countRemoveItalicSign) + countEmojiBefore, length: (rangeItalic[i].endIndex + countEmoji + 1) - lastFirstRange))
  590. if !isEditing{
  591. finalText.mutableString.replaceOccurrences(of: "\(italicSign)", with: "", options: .literal, range: NSRange(location: lastFirstRange + countEmojiBefore - (2*countRemoveItalicSign), length: 1))
  592. finalText.mutableString.replaceOccurrences(of: "\(italicSign)", with: "", options: .literal, range: NSRange(location: rangeItalic[i].endIndex + totalEmoji - (2*countRemoveItalicSign) - 1, length: 1))
  593. countRemoveItalicSign += 1
  594. } else {
  595. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: lastFirstRange + countEmojiBefore, length: 1))
  596. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: rangeItalic[i].endIndex + totalEmoji, length: 1))
  597. }
  598. lastFirstRange = 0
  599. }
  600. }
  601. }
  602. //Underline
  603. let textAfterItalic = finalText.string
  604. let rangeUnderline = getRangeOfWordWithSign(sentence: textAfterItalic, sign: underlineSign)
  605. if rangeUnderline.count > 0 {
  606. var lastFirstRange = 0
  607. var countRemoveUnderlineSign = 0
  608. var continueCheckingUnderline = false
  609. var totalEmoji = 0
  610. for i in 0..<rangeUnderline.count {
  611. if lastFirstRange == 0 {
  612. if (rangeUnderline[i].startIndex == 0 || checkCharBeforeAfter(char: textAfterItalic.substring(from: rangeUnderline[i].startIndex - 1, to: rangeUnderline[i].startIndex - 1))) {
  613. lastFirstRange = rangeUnderline[i].startIndex
  614. continueCheckingUnderline = true
  615. } else {
  616. continueCheckingUnderline = false
  617. }
  618. }
  619. if !continueCheckingUnderline {
  620. continue
  621. }
  622. if (rangeUnderline[i].endIndex == textAfterItalic.count - 1 || checkCharBeforeAfter(char: textAfterItalic.substring(from: rangeUnderline[i].endIndex + 1, to: rangeUnderline[i].endIndex + 1))) {
  623. let countEmojiBefore = finalText.string.substring(from: 0, to: lastFirstRange - (2*countRemoveUnderlineSign)).countEmojiCharacter()
  624. let countEmoji = finalText.string.substring(from: lastFirstRange - (2*countRemoveUnderlineSign), to: rangeUnderline[i].endIndex - (2*countRemoveUnderlineSign)).countEmojiCharacter()
  625. totalEmoji = countEmoji + countEmojiBefore
  626. finalText.addAttribute(.underlineStyle, value: NSUnderlineStyle.thick.rawValue, range: NSRange(location: lastFirstRange - (2*countRemoveUnderlineSign) + countEmojiBefore + 1, length: (rangeUnderline[i].endIndex + countEmoji - 1) - lastFirstRange))
  627. if !isEditing{
  628. finalText.mutableString.replaceOccurrences(of: "\(underlineSign)", with: "", options: .literal, range: NSRange(location: lastFirstRange + countEmojiBefore - (2*countRemoveUnderlineSign), length: 1))
  629. finalText.mutableString.replaceOccurrences(of: "\(underlineSign)", with: "", options: .literal, range: NSRange(location: rangeUnderline[i].endIndex + totalEmoji - (2*countRemoveUnderlineSign) - 1, length: 1))
  630. countRemoveUnderlineSign += 1
  631. } else {
  632. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: lastFirstRange + countEmojiBefore, length: 1))
  633. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: rangeUnderline[i].endIndex + totalEmoji, length: 1))
  634. }
  635. lastFirstRange = 0
  636. }
  637. }
  638. }
  639. //Strikethrough
  640. let textAfterUnderline = finalText.string
  641. let rangeStrikethrough = getRangeOfWordWithSign(sentence: textAfterUnderline, sign: strikethroughSign)
  642. if rangeStrikethrough.count > 0 {
  643. var lastFirstRange = 0
  644. var countRemoveStrikethroughSign = 0
  645. var continueCheckingStrikethrough = false
  646. var totalEmoji = 0
  647. for i in 0..<rangeStrikethrough.count {
  648. if lastFirstRange == 0 {
  649. if (rangeStrikethrough[i].startIndex == 0 || checkCharBeforeAfter(char: textAfterUnderline.substring(from: rangeStrikethrough[i].startIndex - 1, to: rangeStrikethrough[i].startIndex - 1))) {
  650. lastFirstRange = rangeStrikethrough[i].startIndex
  651. continueCheckingStrikethrough = true
  652. } else {
  653. continueCheckingStrikethrough = false
  654. }
  655. }
  656. if !continueCheckingStrikethrough {
  657. continue
  658. }
  659. if (rangeStrikethrough[i].endIndex == textAfterUnderline.count - 1 || checkCharBeforeAfter(char: textAfterUnderline.substring(from: rangeStrikethrough[i].endIndex + 1, to: rangeStrikethrough[i].endIndex + 1))) {
  660. let countEmojiBefore = finalText.string.substring(from: 0, to: lastFirstRange - (2*countRemoveStrikethroughSign)).countEmojiCharacter()
  661. let countEmoji = finalText.string.substring(from: lastFirstRange - (2*countRemoveStrikethroughSign), to: rangeStrikethrough[i].endIndex - (2*countRemoveStrikethroughSign)).countEmojiCharacter()
  662. totalEmoji = countEmoji + countEmojiBefore
  663. finalText.addAttribute(.strikethroughStyle, value: 2, range: NSRange(location: lastFirstRange - (2*countRemoveStrikethroughSign) + countEmojiBefore + 1, length: (rangeStrikethrough[i].endIndex + countEmoji - 1) - lastFirstRange))
  664. if !isEditing{
  665. finalText.mutableString.replaceOccurrences(of: "\(strikethroughSign)", with: "", options: .literal, range: NSRange(location: lastFirstRange + countEmojiBefore - (2*countRemoveStrikethroughSign), length: 1))
  666. finalText.mutableString.replaceOccurrences(of: "\(strikethroughSign)", with: "", options: .literal, range: NSRange(location: rangeStrikethrough[i].endIndex + totalEmoji - (2*countRemoveStrikethroughSign) - 1, length: 1))
  667. countRemoveStrikethroughSign += 1
  668. } else {
  669. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: lastFirstRange + countEmojiBefore, length: 1))
  670. finalText.addAttribute(.foregroundColor, value: UIColor.gray, range: NSRange(location: rangeStrikethrough[i].endIndex + totalEmoji, length: 1))
  671. }
  672. lastFirstRange = 0
  673. }
  674. }
  675. }
  676. //Check Mention
  677. let finalTextAfterRichText = finalText.string
  678. if finalTextAfterRichText.contains("@") {
  679. if !group_id.isEmpty {
  680. let listMembers = Member.getAllMember(group_id: group_id)
  681. if listMembers.count > 0 {
  682. for i in 0..<listMembers.count {
  683. if isEditing {
  684. if listMentionInTextField.count > 0 {
  685. let name = (listMembers[i].firstName + " " + listMembers[i].lastName).trimmingCharacters(in: .whitespaces)
  686. if listMentionInTextField.firstIndex(where: { ($0.firstName + " " + $0.lastName).trimmingCharacters(in: .whitespaces) == name }) != nil {
  687. let range = NSString(string: finalTextAfterRichText).range(of: "@\(name)", options: .caseInsensitive)
  688. finalText.addAttribute(.foregroundColor, value: UIColor.mentionColor, range: range)
  689. }
  690. }
  691. } else {
  692. let name = (listMembers[i].firstName + " " + listMembers[i].lastName).trimmingCharacters(in: .whitespaces)
  693. let range = NSString(string: finalTextAfterRichText).range(of: listMembers[i].pin, options: .caseInsensitive)
  694. if range.lowerBound != range.upperBound {
  695. finalText.mutableString.replaceOccurrences(of: listMembers[i].pin, with: name, options: .literal, range: range)
  696. finalText.addAttribute(.foregroundColor, value: UIColor.mentionColor, range: NSString(string: finalText.string).range(of: "@\(name)"))
  697. }
  698. }
  699. }
  700. }
  701. } else {
  702. let listTextEnter = finalText.string.split(separator: "\n")
  703. for j in 0...listTextEnter.count - 1 {
  704. let listText = listTextEnter[j].split(separator: " ")
  705. let listMention = listText.filter({ $0.starts(with: "@")})
  706. if listMention.count > 0 {
  707. for i in 0..<listMention.count {
  708. let f_pin = (String(listMention[i])).substring(from: 1, to: listMention[i].count)
  709. let member = Member.getMember(f_pin: f_pin)
  710. if member != nil {
  711. let name = (member!.firstName + " " + member!.lastName).trimmingCharacters(in: .whitespaces)
  712. finalText.mutableString.replaceOccurrences(of: f_pin, with: name, options: .literal, range: NSString(string: finalText.string).range(of: f_pin))
  713. }
  714. }
  715. }
  716. }
  717. }
  718. }
  719. if isSearching {
  720. let range = NSString(string: finalText.string).range(of: textSearch, options: .caseInsensitive) // 2
  721. let highlightColor = UIColor.systemYellow // 3
  722. let highlightedAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.backgroundColor: highlightColor] // 4
  723. finalText.addAttributes(highlightedAttributes, range: range) // 5
  724. }
  725. return finalText
  726. }
  727. func checkCharBeforeAfter(char: String) -> Bool {
  728. return char == " " || char == "\n" || char == "*" || char == "_" || char == "^" || char == "~"
  729. }
  730. func checkStartWithLink() -> Bool {
  731. return self.starts(with: "https://") || self.starts(with: "http://") || self.starts(with: "www.")
  732. //|| 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.")
  733. }
  734. func getRangeOfWordWithSign(sentence: String, sign: Character) -> [Range<Int>] {
  735. let asterisk: Character = sign
  736. var ranges = [Range<Int>]()
  737. var startIndex = sentence.startIndex
  738. while let startRange = sentence[startIndex...].firstIndex(of: asterisk),
  739. let endRange = sentence[startRange...].dropFirst().firstIndex(of: asterisk) {
  740. let range = startRange..<endRange
  741. let word = sentence[range].replacingOccurrences(of: "\(sign)", with: "")
  742. if !word.isEmpty {
  743. let lower = sentence.distance(from: sentence.startIndex, to: startRange)
  744. let upper = sentence.distance(from: sentence.startIndex, to: endRange)
  745. ranges.append(Range(uncheckedBounds: (lower: lower, upper: upper)))
  746. }
  747. startIndex = endRange
  748. }
  749. return ranges
  750. }
  751. }
  752. extension UIFont {
  753. var bold: UIFont {
  754. return with(traits: .traitBold)
  755. } // bold
  756. var italic: UIFont {
  757. return with(traits: .traitItalic)
  758. } // italic
  759. func with(traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
  760. guard let descriptor = self.fontDescriptor.withSymbolicTraits(traits) else {
  761. return self
  762. } // guard
  763. return UIFont(descriptor: descriptor, size: 0)
  764. } // with(traits:)
  765. }
  766. extension UILabel {
  767. public func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat) {
  768. let attachment = NSTextAttachment()
  769. attachment.image = image
  770. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  771. let attachmentStr = NSAttributedString(attachment: attachment)
  772. let mutableAttributedString = NSMutableAttributedString()
  773. mutableAttributedString.append(attachmentStr)
  774. let textString = NSAttributedString(string: text, attributes: [.font: self.font!])
  775. mutableAttributedString.append(textString)
  776. self.attributedText = mutableAttributedString
  777. }
  778. public func setAttributeText(image: UIImage, with textMutable: NSAttributedString, size: CGFloat, y: CGFloat) {
  779. let attachment = NSTextAttachment()
  780. attachment.image = image
  781. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  782. let attachmentStr = NSAttributedString(attachment: attachment)
  783. let mutableAttributedString = NSMutableAttributedString()
  784. mutableAttributedString.append(attachmentStr)
  785. mutableAttributedString.append(textMutable)
  786. self.attributedText = mutableAttributedString
  787. }
  788. }
  789. extension Bundle {
  790. public static func resourceBundle(for frameworkClass: AnyClass) -> Bundle {
  791. let frameworkBundle = Bundle(for: frameworkClass)
  792. guard let resourceBundleURL = frameworkBundle.url(forResource: "DigiXLite", withExtension: "bundle"),
  793. let resourceBundle = Bundle(url: resourceBundleURL) else {
  794. return frameworkBundle
  795. }
  796. return resourceBundle
  797. }
  798. public static func resourcesMediaBundle(for frameworkClass: AnyClass) -> Bundle {
  799. let frameworkBundle = Bundle(for: frameworkClass)
  800. guard let resourceBundleURL = frameworkBundle.url(forResource: "DigiXLiteResources", withExtension: "bundle"),
  801. let resourceBundle = Bundle(url: resourceBundleURL) else {
  802. //print(("\(moduleName).bundle not found in \(frameworkBundle)")
  803. return frameworkBundle
  804. }
  805. return resourceBundle
  806. }
  807. }
  808. //extension UIFont {
  809. //
  810. // static func register(from url: URL) throws {
  811. // guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {
  812. // throw fatalError("Could not create font data provider for \(url).")
  813. // }
  814. // let font = CGFont(fontDataProvider)
  815. // var error: Unmanaged<CFError>?
  816. // guard CTFontManagerRegisterGraphicsFont(font!, &error) else {
  817. // throw error!.takeUnretainedValue()
  818. // }
  819. // }
  820. //
  821. //}
  822. extension UIButton {
  823. private func actionHandleBlock(action:(() -> Void)? = nil) {
  824. struct __ {
  825. static var action :(() -> Void)?
  826. }
  827. if action != nil {
  828. __.action = action
  829. } else {
  830. __.action?()
  831. }
  832. }
  833. @objc private func triggerActionHandleBlock() {
  834. self.actionHandleBlock()
  835. }
  836. public func actionHandle(controlEvents control :UIControl.Event, ForAction action:@escaping () -> Void) {
  837. self.actionHandleBlock(action: action)
  838. self.addTarget(self, action: #selector(self.triggerActionHandleBlock), for: control)
  839. }
  840. }
  841. extension UINavigationController {
  842. func replaceAllViewController(with viewController: UIViewController, animated: Bool) {
  843. pushViewController(viewController, animated: animated)
  844. viewControllers.removeSubrange(1...viewControllers.count - 2)
  845. }
  846. var rootViewController : UIViewController? {
  847. return viewControllers.first
  848. }
  849. func popViewController(animated: Bool, completion: @escaping () -> Void) {
  850. popViewController(animated: animated)
  851. if animated, let coordinator = transitionCoordinator {
  852. coordinator.animate(alongsideTransition: nil) { _ in
  853. completion()
  854. }
  855. } else {
  856. completion()
  857. }
  858. }
  859. }
  860. extension UIImageView {
  861. private static var taskKey = 0
  862. private static var urlKey = 0
  863. private var currentTask: URLSessionTask? {
  864. get { return objc_getAssociatedObject(self, &UIImageView.taskKey) as? URLSessionTask }
  865. set { objc_setAssociatedObject(self, &UIImageView.taskKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  866. }
  867. private var currentURL: URL? {
  868. get { return objc_getAssociatedObject(self, &UIImageView.urlKey) as? URL }
  869. set { objc_setAssociatedObject(self, &UIImageView.urlKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
  870. }
  871. func loadImageAsync(with urlString: String?) {
  872. // cancel prior task, if any
  873. weak var oldTask = currentTask
  874. currentTask = nil
  875. oldTask?.cancel()
  876. // reset imageview's image
  877. self.image = nil
  878. // allow supplying of `nil` to remove old image and then return immediately
  879. guard let urlString = urlString else { return }
  880. // check cache
  881. if let cachedImage = ImageCache.shared.image(forKey: urlString) {
  882. self.image = cachedImage
  883. return
  884. }
  885. // download
  886. let url = URL(string: urlString)!
  887. currentURL = url
  888. let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
  889. self?.currentTask = nil
  890. //error handling
  891. if let error = error {
  892. // don't bother reporting cancelation errors
  893. if (error as NSError).domain == NSURLErrorDomain && (error as NSError).code == NSURLErrorCancelled {
  894. return
  895. }
  896. //print(error)
  897. return
  898. }
  899. guard let data = data, let downloadedImage = UIImage(data: data) else {
  900. //print(("unable to extract image")
  901. return
  902. }
  903. ImageCache.shared.save(image: downloadedImage, forKey: urlString)
  904. if url == self?.currentURL {
  905. DispatchQueue.main.async {
  906. self?.image = downloadedImage
  907. }
  908. }
  909. }
  910. // save and start new task
  911. currentTask = task
  912. task.resume()
  913. }
  914. private func actionHandleBlock(action:(() -> Void)? = nil) {
  915. struct __ {
  916. static var action :(() -> Void)?
  917. }
  918. if action != nil {
  919. __.action = action
  920. } else {
  921. __.action?()
  922. }
  923. }
  924. @objc private func triggerActionHandleBlock() {
  925. self.actionHandleBlock()
  926. }
  927. func actionHandle(controlEvents control :UIControl.Event, ForAction action:@escaping () -> Void) {
  928. self.actionHandleBlock(action: action)
  929. self.isUserInteractionEnabled = true
  930. self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.triggerActionHandleBlock)))
  931. }
  932. }
  933. extension UITextField {
  934. public enum PaddingSide {
  935. case left(CGFloat)
  936. case right(CGFloat)
  937. case both(CGFloat)
  938. }
  939. public func addPadding(_ padding: PaddingSide) {
  940. self.leftViewMode = .always
  941. self.layer.masksToBounds = true
  942. switch padding {
  943. case .left(let spacing):
  944. let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
  945. self.leftView = paddingView
  946. self.rightViewMode = .always
  947. case .right(let spacing):
  948. let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
  949. self.rightView = paddingView
  950. self.rightViewMode = .always
  951. case .both(let spacing):
  952. let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: spacing, height: self.frame.height))
  953. // left
  954. self.leftView = paddingView
  955. self.leftViewMode = .always
  956. // right
  957. self.rightView = paddingView
  958. self.rightViewMode = .always
  959. }
  960. }
  961. }
  962. class ImageCache {
  963. private let cache = NSCache<NSString, UIImage>()
  964. private var observer: NSObjectProtocol!
  965. static let shared = ImageCache()
  966. private init() {
  967. // make sure to purge cache on memory pressure
  968. observer = NotificationCenter.default.addObserver(forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: nil) { [weak self] notification in
  969. self?.cache.removeAllObjects()
  970. }
  971. }
  972. deinit {
  973. NotificationCenter.default.removeObserver(observer as Any)
  974. }
  975. func image(forKey key: String) -> UIImage? {
  976. return cache.object(forKey: key as NSString)
  977. }
  978. func save(image: UIImage, forKey key: String) {
  979. cache.setObject(image, forKey: key as NSString)
  980. }
  981. }
  982. public class LibAlertController: UIAlertController {
  983. public override func viewWillAppear(_ animated: Bool) {
  984. super.viewWillAppear(animated)
  985. // Customize the title's font
  986. let titleFont = UIFont.boldSystemFont(ofSize: 16)
  987. let titleAttributes = [NSAttributedString.Key.font: titleFont]
  988. setValue(NSAttributedString(string: self.title ?? "", attributes: titleAttributes), forKey: "attributedTitle")
  989. // Change the font for the message
  990. let messageFont = UIFont.systemFont(ofSize: 14)
  991. let messageAttributes = [NSAttributedString.Key.font: messageFont]
  992. setValue(NSAttributedString(string: self.message ?? "", attributes: messageAttributes), forKey: "attributedMessage")
  993. for i in self.actions {
  994. let attributedText = NSAttributedString(string: i.title ?? "", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)])
  995. guard let label = (i.value(forKey: "__representer") as AnyObject).value(forKey: "label") as? UILabel else { return }
  996. label.attributedText = attributedText
  997. }
  998. }
  999. }
  1000. extension UISearchBar
  1001. {
  1002. func setMagnifyingGlassColorTo(color: UIColor)
  1003. {
  1004. // Search Icon
  1005. let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
  1006. let glassIconView = textFieldInsideSearchBar?.leftView as? UIImageView
  1007. glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
  1008. glassIconView?.tintColor = color
  1009. }
  1010. func setClearButtonColorTo(color: UIColor)
  1011. {
  1012. // Clear Button
  1013. let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
  1014. let crossIconView = textFieldInsideSearchBar?.value(forKey: "clearButton") as? UIButton
  1015. crossIconView?.setImage(crossIconView?.currentImage?.withRenderingMode(.alwaysTemplate), for: .normal)
  1016. crossIconView?.tintColor = color
  1017. }
  1018. func setPlaceholderTextColorTo(color: UIColor)
  1019. {
  1020. let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
  1021. textFieldInsideSearchBar?.textColor = color
  1022. let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
  1023. textFieldInsideSearchBarLabel?.textColor = color
  1024. }
  1025. }
  1026. extension String {
  1027. init(unicodeScalar: UnicodeScalar) {
  1028. self.init(Character(unicodeScalar))
  1029. }
  1030. init?(unicodeCodepoint: Int) {
  1031. if let unicodeScalar = UnicodeScalar(unicodeCodepoint) {
  1032. self.init(unicodeScalar: unicodeScalar)
  1033. } else {
  1034. return nil
  1035. }
  1036. }
  1037. static func +(lhs: String, rhs: Int) -> String {
  1038. return lhs + String(unicodeCodepoint: rhs)!
  1039. }
  1040. static func +=(lhs: inout String, rhs: Int) {
  1041. lhs = lhs + rhs
  1042. }
  1043. }