ConfigUtils.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. //
  2. // ResourceAllocationUtils.swift
  3. // MTP2_iOS
  4. //
  5. // Created by Muchinfo on 2018/6/28.
  6. // Copyright © 2018年 Muchinfo. All rights reserved.
  7. //
  8. import Foundation
  9. import Reachability
  10. import SwiftDate
  11. enum ConfigType: String {
  12. case appVersion = "appVersion"
  13. case url = "url"
  14. }
  15. /// 通用配置工具类
  16. class ConfigUtils {
  17. /// getValue
  18. /// - Parameter key: key
  19. /// - Returns: Any
  20. static func getValue(key: ConfigType) -> Any? {
  21. if let path = Bundle.main.path(forResource: "Config", ofType: "plist"), let dic = NSDictionary(contentsOfFile: path) {
  22. return dic[key.rawValue]
  23. }
  24. return nil
  25. }
  26. /// 资源类型
  27. ///
  28. /// - mineFunctionModule: 我的模块功能项
  29. /// - functionModule: 大功能模块
  30. /// - payWay: 支付方式
  31. /// - tradeLink: 链路信息模块
  32. /// - supportOAuth: 是否支持三方登录
  33. /// - isShowTotleVolume: 是否展示成交量
  34. /// - SupportResetPwd 是否支持重置密码
  35. /// - SupportMobileLogin 是否支持手机登录
  36. /// - AreaUrl: 通用地址
  37. enum ResourceType: String {
  38. case mineFunctionModule = "mine's function module"
  39. case functionModule = "function module"
  40. case payWay = "pay way"
  41. case tradeLink = "trade link"
  42. case supportOAuth = "SupportOAuth"
  43. case SupportResetPwd = "SupportResetPwd"
  44. case SupportMobileLogin = "SupportMobileLogin"
  45. case UpdateUrl = "UpdateUrl"
  46. case AreaUrl = "areaUrl"
  47. }
  48. /// getValue
  49. /// - Parameter key: ResourceType
  50. /// - Returns: Any
  51. static func getValue(key: ResourceType) -> Any? {
  52. if let appVersion = ConfigUtils.getValue(key: .appVersion) as? String,
  53. let path = Bundle.main.path(forResource: appVersion, ofType: ".plist"),
  54. let dic = NSDictionary(contentsOfFile: path) {
  55. return dic[key.rawValue]
  56. }
  57. return nil
  58. }
  59. /// 获取对应服务的服务地址信息
  60. /// - Parameter type: type
  61. /// - Returns: String
  62. static func getServiceUrl(resourceType type: ResourceType) -> String? {
  63. /// 判断是否第一次运行
  64. guard let array = ConfigUtils.getValue(key: .tradeLink) as? Array<Dictionary<String, Any>> else {
  65. dPrint("【\(#function)】错误的配置文件")
  66. return ""
  67. }
  68. switch type {
  69. case .AreaUrl: /// 通用地址
  70. #if DEBUG
  71. return (array[0]["addressUrl"] as? String) ?? ""
  72. #else
  73. return (array[0]["addressUrl_release"] as? String) ?? ""
  74. #endif
  75. case .UpdateUrl: /// app更新地址
  76. return (array[0]["updateUrl"] as? String) ?? ""
  77. default:
  78. return ""
  79. }
  80. }
  81. }
  82. /// 错误码工具类
  83. class ErrorCodeUtils {
  84. static func getValue(key: String) -> Any? {
  85. if let path = Bundle.main.path(forResource: "ErrorCode", ofType: "plist"), let dic = NSDictionary(contentsOfFile: path) {
  86. return dic[key]
  87. }
  88. return nil
  89. }
  90. }
  91. /// 错误信息工具类
  92. class ErrorUtils {
  93. static func desc(_ errorCode: Int?) -> String {
  94. /// 先判断网络装药
  95. let reachability = try! Reachability()
  96. /// 检测网络连接状态
  97. if reachability.connection != .unavailable {
  98. /// 先尝试从数据库中获取
  99. let entity = try? DatabaseHelper.getError(errorcode: "\(errorCode ?? -60001)")
  100. if entity != nil { return entity!.errordesc! }
  101. /// 再深度从自定义错误中获取
  102. if let errorMessage = ErrorCodeUtils.getValue(key: String(errorCode ?? -60001)) as? String { return errorMessage }
  103. return "请求超时"
  104. }
  105. return "当前网络不可用"
  106. }
  107. }
  108. /// 合规性校验工具
  109. class RegularUtils {
  110. /// 检查电话号码
  111. ///
  112. /// - Parameter str: 待校验字符串
  113. /// - Returns: 是否验证通过
  114. static func checkPhoneNumber(with str: String) -> Bool {
  115. let regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$"
  116. let test = NSPredicate(format: "SELF MATCHES %@", regex)
  117. return test.evaluate(with: str)
  118. }
  119. /// 校验只包含数字
  120. ///
  121. /// - Parameter str: 待校验字符串
  122. /// - Returns: 是否验证通过
  123. static func checkNumber(with str: String) -> Bool {
  124. let regex = "\\d+"
  125. let test = NSPredicate(format: "SELF MATCHES %@", regex)
  126. return test.evaluate(with: str)
  127. }
  128. /// 校验是否有效身份证号码
  129. /// - Parameter cardNo: 身份证号码
  130. /// - Returns: 校验结果
  131. static func isValidIDCard(_ cardNo: String) -> Bool {
  132. let regex = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$"
  133. let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
  134. /// 校验18位有效身份证
  135. if !predicate.evaluate(with: cardNo) || cardNo.count != 18 {
  136. return false
  137. }
  138. /// 将前17位加权因子保存在数组里
  139. let idCardWiArray = ["7", "9", "10", "5", "8", "4", "2", "1", "6", "3", "7", "9", "10", "5", "8", "4", "2"]
  140. /// 这是除以11后,可能产生的11位余数、验证码,也保存成数组
  141. let idCardYArray = ["1", "0", "10", "9", "8", "7", "6", "5", "4", "3", "2"]
  142. /// 用来保存前17位各自乖以加权因子后的总和
  143. var idCardWiSum = 0
  144. for i in 0..<17 {
  145. let subStrIndex = Int(NSString(string: cardNo).substring(with: NSRange(location: i, length: 1)))!
  146. let idCardWiIndex = Int(idCardWiArray[i])!
  147. idCardWiSum += subStrIndex*idCardWiIndex
  148. }
  149. /// 计算出校验码所在数组的位置
  150. let idCardMod=idCardWiSum%11
  151. /// 得到最后一位身份证号码
  152. let idCardLast = NSString(string: cardNo).substring(with: NSRange(location: 17, length: 1))
  153. /// 不管大小写都过
  154. if idCardMod == 2 {
  155. if idCardLast.uppercased() != "X" {
  156. return false
  157. }
  158. } else {
  159. /// 用计算出的验证码与最后一位身份证号码匹配,如果一致,说明通过,否则是无效的身份证号码
  160. if idCardLast != idCardYArray[idCardMod] {
  161. return false
  162. }
  163. }
  164. return true
  165. }
  166. /// 密码校验
  167. ///
  168. /// - Parameter str: 待校验字符串
  169. /// - Returns: 是否验证通过
  170. static func checkAllCharactersPatten(check str: String) -> Bool {
  171. let lowercase = ".*[a-z]+.*"
  172. let captial = ".*[A-Z]+.*"
  173. let number = ".*[0-9]+.*"
  174. let punctuation = ".*[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]+.*"
  175. let test1 = NSPredicate(format: "SELF MATCHES %@", lowercase)
  176. let test2 = NSPredicate(format: "SELF MATCHES %@", captial)
  177. let test3 = NSPredicate(format: "SELF MATCHES %@", number)
  178. let test4 = NSPredicate(format: "SELF MATCHES %@", punctuation)
  179. var regularNum = 0
  180. if test1.evaluate(with: str) {
  181. regularNum += 1
  182. }
  183. if test2.evaluate(with: str) {
  184. regularNum += 1
  185. }
  186. if test3.evaluate(with: str) {
  187. regularNum += 1
  188. }
  189. if test4.evaluate(with: str) {
  190. regularNum += 1
  191. }
  192. return regularNum >= 3
  193. }
  194. /// 校验证件号
  195. ///
  196. /// - Parameter str: 待检验字符串
  197. /// - Returns: 是否验证通过
  198. static func checkCertificate(with str: String) -> Bool {
  199. if str.count > 30 || str.contains("{") || str.contains("}") || str.contains("(") || str.contains(")") || str.contains("*") {
  200. return false
  201. } else {
  202. return true
  203. }
  204. }
  205. static func stringPaddedForBase64(_ base64String: String) -> String {
  206. let paddedLength = base64String.count + (base64String.count%3)
  207. return base64String.padding(toLength: paddedLength, withPad: "=", startingAt: 0)
  208. }
  209. }
  210. /// 日期工具类
  211. class DateUtils {
  212. /// 判断两个日期是否在同年的同一个月
  213. static func judgeSameYearMonth(target: Date, source: Date = Date()) -> Bool {
  214. let calendar = Calendar.current
  215. let targetComponents = calendar.dateComponents(Set<Calendar.Component>([.year, .month]), from: target)
  216. let sourceComponents = calendar.dateComponents(Set<Calendar.Component>([.year, .month]), from: source)
  217. if calendar.date(from: targetComponents)!.compare(calendar.date(from: sourceComponents)!) == .orderedSame {
  218. return true
  219. }
  220. return false
  221. }
  222. /// 获取带T的时间戳的时间字符串
  223. /// - Parameter dateString: dateString
  224. /// - Returns: String
  225. static func getTDateString(_ dateString: String, _ formatter: String = "yyyy-MM-dd") -> String {
  226. let dateFormatter = DateFormatter()
  227. let tempLocale = dateFormatter.locale
  228. dateFormatter.locale = Locale(identifier: "en_US_POSIX")
  229. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
  230. let date = dateFormatter.date(from: dateString) ?? Date()
  231. dateFormatter.dateFormat = formatter
  232. dateFormatter.locale = tempLocale
  233. return dateFormatter.string(from: date)
  234. }
  235. /// 获取带T的时间戳的时间字符串
  236. /// - Parameter dateString: dateString
  237. /// - Returns: String
  238. static func getTDate(_ dateString: String, _ formatter: String = "yyyy-MM-dd") -> Date {
  239. let string = dateString.getTDateString()
  240. guard let date = string.toDate(formatter: formatter) else { return Date() }
  241. return date
  242. }
  243. /// 获取两个时间戳间隔时分秒
  244. /// - Parameters:
  245. /// - timer1: timer1
  246. /// - timer2: timer2
  247. /// - count: count
  248. /// - Returns: String
  249. static func diffs(_ timer1: TimeInterval, _ timer2: TimeInterval, _ count: Double) -> DateComponents? {
  250. let formatter = DateFormatter()
  251. formatter.dateStyle = .medium
  252. formatter.timeStyle = .short
  253. formatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
  254. let date1 = Date(timeIntervalSince1970: timer1-count)
  255. let date2 = Date(timeIntervalSince1970: timer2)
  256. /// 日历对象(方便比较两个日期之间的差距)
  257. let calendar = Calendar.current
  258. return calendar.dateComponents(Set<Calendar.Component>([.hour, .minute, .second]), from: date1, to: date2)
  259. }
  260. }
  261. /// 以后用这个方法输出log信息,可以在release下剔除log
  262. ///
  263. /// - Parameter item: 输出内容
  264. func dPrint(_ item: @autoclosure () -> Any) {
  265. #if DEBUG
  266. debugPrint(item())
  267. #endif
  268. }