PQCommonMethodUtil.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. //
  2. // PQCommonMethodUtil.swift
  3. // PQSpeed
  4. //
  5. // Created by lieyunye on 2020/5/29.
  6. // Copyright © 2020 BytesFlow. All rights reserved.
  7. //
  8. import AdSupport
  9. import Alamofire
  10. import Foundation
  11. import KeychainAccess
  12. import Kingfisher
  13. import KingfisherWebP
  14. import Photos
  15. import Toast_Swift
  16. /// Home文件地址
  17. public let homeDirectory = NSHomeDirectory()
  18. /// docdocumens文件地址
  19. public let documensDirectory = homeDirectory + "/Documents"
  20. /// library文件地址
  21. public let libraryDirectory = homeDirectory + "/Library"
  22. /// 本地存储资源地址
  23. public let resourceDirectory = documensDirectory + "/Resource"
  24. /// 播放视频缓冲本地沙河目录
  25. public let videoCacheDirectory = resourceDirectory + "/VideoCache"
  26. /// 相册视频导出到本地沙河目录
  27. public let photoLibraryDirectory = resourceDirectory + "/PhotoLibrary/"
  28. /// 背景音乐导出到本地沙河目录
  29. public let bgMusicDirectory = resourceDirectory + "/BGMusic/"
  30. /// 网络视频素材下载到本地沙河目录
  31. public let downloadDirectory = resourceDirectory + "/Download/"
  32. /// 网络图片、GIF 素材下载到本地沙河目录
  33. public let downloadImagesDirectory = resourceDirectory + "/DownloadImages/"
  34. /// 临时缓存本地沙河目录地址
  35. public let tempDirectory = resourceDirectory + "/Temp/"
  36. /// 导出声音的本地沙盒目录v
  37. public let exportAudiosDirectory = resourceDirectory + "/ExportAudios/"
  38. /// 导出合成视频的本地沙盒目录
  39. public let exportVideosDirectory = resourceDirectory + "/ExportVideos/"
  40. // 版本构建号
  41. public let versionCode = "\(Bundle.main.infoDictionary?["CFBundleVersion"] ?? "1")"
  42. // 版本号
  43. public let versionName = "\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? "1.0.0")"
  44. /// 创建目录文件
  45. /// - Returns: <#description#>
  46. public func createDirectory(path: String) {
  47. let fileManager = FileManager.default
  48. if !fileManager.fileExists(atPath: path) {
  49. try? fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
  50. }
  51. }
  52. /// 判断文件夹是否存在
  53. /// - Parameter dicPath:文件夹 目录
  54. public func directoryIsExists(dicPath: String) -> Bool {
  55. BFLog(message: " dir path is: \(dicPath)")
  56. var directoryExists = ObjCBool(false)
  57. let fileExists = FileManager.default.fileExists(atPath: dicPath, isDirectory: &directoryExists)
  58. return fileExists && directoryExists.boolValue
  59. }
  60. /// 判断文件是否存在
  61. /// - Parameter filepath: 文件目录
  62. public func fileIsExists(filePath: String) -> Bool {
  63. BFLog(message: "file path is: \(filePath)")
  64. let fileExists = FileManager.default.fileExists(atPath: filePath)
  65. return fileExists
  66. }
  67. /// 创建沙河文件地址
  68. /// - Parameter url: 原地址
  69. /// - Returns: <#description#>
  70. public func createFilePath(url: String) -> Bool {
  71. let fileManager = FileManager.default
  72. if !fileManager.fileExists(atPath: url) {
  73. let isFinished = fileManager.createFile(atPath: url, contents: nil, attributes: nil)
  74. return isFinished
  75. }
  76. return true
  77. }
  78. public func cIPHONE_X() -> Bool {
  79. guard #available(iOS 11.0, *) else {
  80. return false
  81. }
  82. let isX = (UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0) > 0
  83. return isX
  84. }
  85. /// 给按钮/imageView加载网络图片
  86. ///
  87. /// - Parameters:
  88. /// - url: 网络url
  89. /// - mainView: 需要加载的视图
  90. public func netImage(url: String, mainView: Any, placeholder: UIImage = UIImage.moduleImage(named: "placehold_image", moduleName: "BFCommonKit") ?? UIImage()) {
  91. if mainView is UIImageView {
  92. (mainView as! UIImageView).kf.setImage(with: URL(string: url), placeholder: placeholder, options: url.suffix(5) == ".webp" ? [.processor(WebPProcessor.default), .cacheSerializer(WebPSerializer.default)] : nil, progressBlock: { _, _ in
  93. }) { _ in
  94. }
  95. } else if mainView is UIButton {
  96. (mainView as! UIButton).kf.setImage(with: URL(string: url), for: .normal, placeholder: placeholder, options: url.suffix(5) == ".webp" ? [.processor(WebPProcessor.default), .cacheSerializer(WebPSerializer.default)] : nil, progressBlock: { _, _ in
  97. }) { _ in
  98. }
  99. }
  100. }
  101. /** 获取Kingfisher缓存的图片的data */
  102. public func kf_imageCacheData(originUrl: String) -> Data? {
  103. let diskCachePath = ImageCache.default.cachePath(forKey: originUrl)
  104. let data = try? Data(contentsOf: URL(fileURLWithPath: diskCachePath))
  105. return data
  106. }
  107. /** 获取Kingfisher缓存的图片 */
  108. public func kf_imageCacheImage(originUrl: String, completeHandle: @escaping (_ image: UIImage?, _ error: Error?) -> Void) {
  109. ImageCache.default.retrieveImageInDiskCache(forKey: originUrl, options: [.cacheOriginalImage]) { result in
  110. DispatchQueue.main.async {
  111. switch result {
  112. case let .success(image):
  113. completeHandle(image, nil)
  114. case let .failure(error):
  115. completeHandle(nil, error)
  116. }
  117. }
  118. }
  119. }
  120. /** 打印 */
  121. public func BFLog<T>(message: T) {
  122. // if PQBFConfig.shared.enableBFLog {
  123. let logger = NXLogger.shared
  124. logger.level = .info
  125. logger.ouput = .debuggerConsole
  126. logger.d(message as? String ?? "")
  127. // } else {
  128. // BuglyLog.level(.warn, logs: message as? String)
  129. // }
  130. }
  131. public func HHZPrint<T>(_: T, file _: String = #file, funcName _: String = #function, lineNum _: Int = #line) {
  132. #if DEBUG
  133. // let file = (file as NSString).lastPathComponent;
  134. //
  135. // print("hhz-\(file):(\(lineNum))--\(message)");
  136. #endif
  137. }
  138. // MARK: 获取公共参数
  139. public func commonParams() -> [String: Any] {
  140. let model = UIDevice.current.model
  141. let systemName = UIDevice.current.systemName
  142. let systemVersion = UIDevice.current.systemVersion
  143. let localizedModel = UIDevice.current.localizedModel
  144. let machineInfo: [String: Any] = [
  145. "model": model, "system": systemName + " " + systemVersion, "brand": localizedModel, "platform": "iOS", "networkType": networkStatus(), "clientIp": ipAddress(),
  146. ]
  147. var commParams: [String: Any] = [
  148. "appVersionCode": versionCode,
  149. "versionCode": versionCode,
  150. "system": systemName + " " + systemVersion,
  151. "systemVersion": systemName + " " + systemVersion,
  152. "appType": PQBFConfig.shared.appType,
  153. "appId": PQBFConfig.shared.appId,
  154. "machineCode": getMachineCode(),
  155. "networkType": networkStatus(),
  156. "ipAddress": ipAddress(),
  157. "clientTimestamp": Int64(Date().timeIntervalSince1970 * 1000),
  158. "platform": "iOS",
  159. "versionName": versionName,
  160. "mid": getMachineCode(),
  161. "machineInfo": dictionaryToJsonString(machineInfo) ?? "",
  162. "requestId": getUniqueId(desc: "requestId"),
  163. "idfa": ASIdentifierManager.shared().advertisingIdentifier.uuidString,
  164. "idfv": UIDevice.current.identifierForVendor?.uuidString ?? "",
  165. "sessionId": PQBFConfig.shared.sessionId,
  166. "subSessionId": PQBFConfig.shared.subSessionId ?? PQBFConfig.shared.sessionId,
  167. ]
  168. if PQBFConfig.shared.token != nil, (PQBFConfig.shared.token?.count ?? 0) > 0 {
  169. commParams["token"] = PQBFConfig.shared.token ?? ""
  170. }
  171. if PQBFConfig.shared.loginUid != nil, (PQBFConfig.shared.loginUid?.count ?? 0) > 0 {
  172. commParams["loginUid"] = PQBFConfig.shared.loginUid ?? ""
  173. commParams["uid"] = PQBFConfig.shared.loginUid ?? ""
  174. }
  175. if PQBFConfig.shared.deviceToken != nil, (PQBFConfig.shared.deviceToken?.count ?? 0) > 0 {
  176. commParams["deviceToken"] = PQBFConfig.shared.deviceToken ?? ""
  177. }
  178. return commParams
  179. }
  180. /// 获取网络状态
  181. /// - Returns: <#description#>
  182. public func networkStatus() -> String {
  183. let status = NetworkReachabilityManager(host: "www.baidu.com")?.status
  184. var statusStr: String!
  185. switch status {
  186. case .unknown:
  187. statusStr = "NETWORK_UNKNOWN"
  188. case .notReachable:
  189. statusStr = "NETWORK_NO"
  190. case .reachable(.cellular):
  191. statusStr = "4G/5G"
  192. case .reachable(.ethernetOrWiFi):
  193. statusStr = "Wi-Fi"
  194. default:
  195. statusStr = "NETWORK_UNKNOWN"
  196. }
  197. return statusStr
  198. }
  199. /// 判断是否有网
  200. /// - Returns: <#description#>
  201. public func isNetConnected() -> Bool {
  202. return NetworkReachabilityManager(host: "www.baidu.com")?.status == .reachable(.cellular) || NetworkReachabilityManager(host: "www.baidu.com")?.status == .reachable(.ethernetOrWiFi)
  203. }
  204. /// 获取ip地址
  205. /// - Returns: <#description#>
  206. public func ipAddress() -> String {
  207. var addresses = [String]()
  208. var ifaddr: UnsafeMutablePointer<ifaddrs>?
  209. if getifaddrs(&ifaddr) == 0 {
  210. var ptr = ifaddr
  211. while ptr != nil {
  212. let flags = Int32(ptr!.pointee.ifa_flags)
  213. var addr = ptr!.pointee.ifa_addr.pointee
  214. if (flags & (IFF_UP | IFF_RUNNING | IFF_LOOPBACK)) == (IFF_UP | IFF_RUNNING) {
  215. if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
  216. var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
  217. if getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0 {
  218. if let address = String(validatingUTF8: hostname) {
  219. addresses.append(address)
  220. }
  221. }
  222. }
  223. }
  224. ptr = ptr!.pointee.ifa_next
  225. }
  226. freeifaddrs(ifaddr)
  227. }
  228. return addresses.first ?? "0.0.0.0"
  229. }
  230. /// 生成唯一ID / 分享跟冷启动
  231. /// - Parameter desc: <#desc description#>
  232. /// - Returns: <#description#>
  233. public func getUniqueId(desc: String) -> String {
  234. let timeStr: String = "\(Date().timeIntervalSince1970)"
  235. let uuid: String = getMachineCode()
  236. let code: String = "\(arc4random_uniform(1_000_000_000))"
  237. let uniqueId = (timeStr + desc + uuid + code).md5.md5
  238. BFLog(message: "生成唯一码:desc = \(desc),timeStr = \(timeStr),uuid = \(uuid),code = \(code),uniqueId = \(uniqueId)")
  239. return uniqueId
  240. }
  241. // MARK: 字典转字符串
  242. public func dictionaryToJsonString(_ dic: [String: Any]) -> String? {
  243. BFLog(message: "dictionaryToJsonString = \(dic)")
  244. if !JSONSerialization.isValidJSONObject(dic) {
  245. return ""
  246. }
  247. guard let data = try? JSONSerialization.data(withJSONObject: dic, options: []) else {
  248. return ""
  249. }
  250. BFLog(message: "dictionaryToJsonString - data = \(data)")
  251. let str = String(data: data, encoding: String.Encoding.utf8)
  252. BFLog(message: "dictionaryToJsonString - str = \(String(describing: str))")
  253. return str
  254. }
  255. // MARK: 字符串转字典
  256. public func jsonStringToDictionary(_ str: String) -> [String: Any]? {
  257. if str.count <= 0 {
  258. return [:]
  259. }
  260. let data = str.data(using: String.Encoding.utf8)
  261. if data == nil || (data?.count ?? 0) <= 0 {
  262. return [:]
  263. }
  264. if let dict = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any] {
  265. return dict
  266. }
  267. return [:]
  268. }
  269. // MARK: 字符串转数组
  270. public func jsonStringToArray(_ str: String) -> [[String: String]]? {
  271. let data = str.data(using: String.Encoding.utf8)
  272. if let array = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String: String]] {
  273. return array
  274. }
  275. return nil
  276. }
  277. /// 数组转为string
  278. /// - Parameter array: <#array description#>
  279. /// - Returns: <#description#>
  280. public func arrayToJsonString(_ array: [Any]) -> String {
  281. if !JSONSerialization.isValidJSONObject(array) {
  282. BFLog(message: "无法解析String")
  283. return ""
  284. }
  285. let data: NSData! = try? JSONSerialization.data(withJSONObject: array, options: []) as NSData?
  286. let JSONString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue)
  287. return JSONString! as String
  288. }
  289. /// jsonString转为数组
  290. /// - Parameter jsonString: <#jsonString description#>
  291. /// - Returns: <#description#>
  292. public func jsonStringToArray(jsonString: String) -> [Any]? {
  293. let data = jsonString.data(using: String.Encoding.utf8)
  294. if data == nil {
  295. return nil
  296. }
  297. if let array = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [Any] {
  298. return array
  299. }
  300. return nil
  301. }
  302. /// 计算字符串大小
  303. /// - Parameters:
  304. /// - text: <#text description#>
  305. /// - font: <#font description#>
  306. /// - size: <#size description#>
  307. /// - Returns: <#description#>
  308. public func sizeWithText(attributedText: NSMutableAttributedString? = nil, text: String, font: UIFont, size: CGSize) -> CGSize {
  309. let option = NSStringDrawingOptions.usesLineFragmentOrigin
  310. if attributedText != nil {
  311. let rect: CGRect = attributedText?.boundingRect(with: size, options: option, context: nil) ?? CGRect(origin: CGPoint.zero, size: size)
  312. return rect.size
  313. } else {
  314. let attributes = [NSAttributedString.Key.font: font]
  315. let rect: CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil)
  316. return rect.size
  317. }
  318. }
  319. /// 根据行数计算字符串大小
  320. /// - Parameters:
  321. /// - text: <#text description#>
  322. /// - numberOfLines: <#numberOfLines description#>
  323. /// - font: <#font description#>
  324. /// - maxSize: <#maxSize description#>
  325. /// - Returns: <#description#>
  326. public func sizeTextFits(attributedText: NSMutableAttributedString?, text: String?, numberOfLines: Int, font: UIFont, maxSize: CGSize) -> CGSize {
  327. var newSize: CGSize = CGSize(width: 0, height: 0)
  328. let label = UILabel(frame: CGRect.zero)
  329. label.font = font
  330. label.numberOfLines = numberOfLines
  331. if attributedText != nil {
  332. label.attributedText = attributedText
  333. } else {
  334. label.text = text
  335. }
  336. newSize = label.sizeThatFits(maxSize)
  337. return newSize
  338. }
  339. public func textNumberOfLines(text: String, font: UIFont, maxSize _: CGSize) -> Int {
  340. let label = UILabel(frame: CGRect.zero)
  341. label.font = font
  342. label.numberOfLines = 0
  343. label.text = text
  344. return label.numberOfLines
  345. }
  346. /// 生成渐变色
  347. /// - Parameters:
  348. /// - size: <#size description#>
  349. /// - endPoint: <#endPoint description#>
  350. /// - startColor: <#startColor description#>
  351. /// - endColor: <#endColor description#>
  352. /// - Returns: <#description#>
  353. public func gradientColor(size: CGSize, endPoint: CGPoint, startColor: UIColor, endColor: UIColor) -> UIColor {
  354. let gradientLayer = CAGradientLayer()
  355. gradientLayer.frame = CGRect(origin: CGPoint(), size: size)
  356. gradientLayer.startPoint = CGPoint.zero
  357. gradientLayer.endPoint = endPoint
  358. gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
  359. UIGraphicsBeginImageContext(size)
  360. gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
  361. let image = UIGraphicsGetImageFromCurrentImageContext()!
  362. return UIColor(patternImage: image)
  363. }
  364. /// 获取设备ID
  365. /// - Returns: <#description#>
  366. public func getMachineCode() -> String {
  367. let userInfo: [String: Any]? = jsonStringToDictionary(UserDefaults.standard.string(forKey: cUserInfoStorageKey) ?? "")
  368. if userInfo != nil && ((userInfo?.keys.contains("isVirtualUser") ?? false) && !(userInfo?["isVirtualUser"] is NSNull) && ((userInfo?["isVirtualUser"] as? Bool) ?? false)) && ((userInfo?.keys.contains("mid") ?? false) && !(userInfo?["mid"] is NSNull)) {
  369. BFLog(message: "虚拟账号mid:\("\(userInfo?["mid"] ?? "")")")
  370. return "\(userInfo?["mid"] ?? "")"
  371. }
  372. let keychain = Keychain(service: "com.piaoquan.pqspeed")
  373. var uuid: String = keychain["machineCode"] ?? ""
  374. if uuid.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
  375. uuid = NSUUID().uuidString
  376. keychain["machineCode"] = uuid
  377. }
  378. BFLog(message: "正式账号mid:\(uuid)")
  379. return uuid
  380. }
  381. /// 显示加载中视图
  382. /// - Parameters:
  383. /// - superView: <#superView description#>
  384. /// - msg: <#msg description#>
  385. /// - Returns: <#description#>
  386. public func cShowHUB(superView: UIView?, msg: String?) {
  387. DispatchQueue.main.async {
  388. if superView == nil {
  389. if msg == nil {
  390. UIApplication.shared.keyWindow?.makeToastActivity(.center)
  391. } else {
  392. UIApplication.shared.keyWindow?.makeToast(msg, duration: 3.0, position: .center)
  393. }
  394. } else {
  395. if msg == nil {
  396. superView!.makeToastActivity(.center)
  397. } else {
  398. superView!.makeToast(msg, duration: 3.0, position: .center)
  399. }
  400. }
  401. }
  402. }
  403. /// 隐藏加载中视图
  404. /// - Parameter superView: <#superView description#>
  405. /// - Returns: <#description#>
  406. public func cHiddenHUB(superView: UIView?) {
  407. DispatchQueue.main.async {
  408. if superView == nil {
  409. UIApplication.shared.keyWindow?.hideAllToasts()
  410. UIApplication.shared.keyWindow?.hideToastActivity()
  411. } else {
  412. superView!.hideAllToasts()
  413. superView?.hideToastActivity()
  414. }
  415. }
  416. }
  417. /// 获取存储值
  418. /// - Parameter key: key description
  419. /// - Returns: description
  420. public func getUserDefaults(key: String) -> Any? {
  421. return UserDefaults.standard.object(forKey: key)
  422. }
  423. /// 存储数据
  424. /// - Parameters:
  425. /// - key: key description
  426. /// - value: value description
  427. /// - Returns: description
  428. public func saveUserDefaults(key: String, value: String) {
  429. UserDefaults.standard.set(value, forKey: key)
  430. UserDefaults.standard.synchronize()
  431. }
  432. /// 存储数据带版本号
  433. /// - Parameters:
  434. /// - key: <#key description#>
  435. /// - value: <#value description#>
  436. public func saveUserDefaultsToJson(key: String, value: Any) {
  437. UserDefaults.standard.set(dictionaryToJsonString([key: value, "appVersionCode": versionCode, "versionName": versionName]), forKey: key)
  438. UserDefaults.standard.synchronize()
  439. }
  440. /// 获取数据带版本号
  441. /// - Parameter key: <#key description#>
  442. /// - Returns: <#description#>
  443. public func getUserDefaultsForJson(key: String) -> Any? {
  444. let jsonStr = UserDefaults.standard.object(forKey: key)
  445. if jsonStr != nil {
  446. return jsonStringToDictionary(jsonStr as! String)?[key]
  447. }
  448. return UserDefaults.standard.object(forKey: key)
  449. }
  450. /// 清空数据
  451. /// - Parameters:
  452. /// - key: key description
  453. /// - value: value description
  454. /// - Returns: description
  455. public func removeUserDefaults(key: String) {
  456. UserDefaults.standard.removeObject(forKey: key)
  457. UserDefaults.standard.synchronize()
  458. }
  459. /// 存储数据
  460. /// - Parameters:
  461. /// - key: key description
  462. /// - value: value description
  463. /// - Returns: description
  464. public func saveUserDefaults(key: String, value: Any) {
  465. UserDefaults.standard.set(value, forKey: key)
  466. UserDefaults.standard.synchronize()
  467. }
  468. /// 保存自定义model as NSArray 当 OBJ 是数组时不能使用 Array 要使用 NSArray
  469. /// - Parameter object: <#object description#>
  470. /// - Parameter key: <#key description#>
  471. public func saveCustomObject(customObject object: NSCoding, key: String) {
  472. let encodedObject = NSKeyedArchiver.archivedData(withRootObject: object)
  473. UserDefaults.standard.set(encodedObject, forKey: key)
  474. UserDefaults.standard.synchronize()
  475. BFLog(message: "保存自定义类成功 key is \(key) \(encodedObject.count)")
  476. }
  477. /// 取自定义model
  478. /// - Parameter key: <#key description#>
  479. public func getCustomObject(forKey key: String) -> AnyObject? {
  480. let decodedObject = UserDefaults.standard.object(forKey: key) as? Data
  481. if decodedObject == nil {
  482. BFLog(message: "key is \(key) decodedObject is nil")
  483. }
  484. if let decoded = decodedObject {
  485. let object = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data)
  486. return object as AnyObject?
  487. }
  488. return nil
  489. }
  490. /// 添加通知
  491. /// - Parameters:
  492. /// - observer: <#observer description#>
  493. /// - aSelectorName: <#aSelectorName description#>
  494. /// - aName: <#aName description#>
  495. /// - anObject: <#anObject description#>
  496. /// - Returns: <#description#>
  497. public func addNotification(_ observer: Any, selector aSelectorName: Selector, name aName: String, object anObject: Any?) {
  498. PQNotification.addObserver(observer, selector: aSelectorName, name: NSNotification.Name(rawValue: aName), object: anObject)
  499. }
  500. /// 发送通知
  501. /// - Parameter aName: <#aName description#>
  502. /// - Returns: <#description#>
  503. public func postNotification(name aName: String, userInfo: [AnyHashable: Any]? = nil) {
  504. PQNotification.post(name: NSNotification.Name(aName), object: nil, userInfo: userInfo)
  505. }
  506. /// 获取是否打开推送
  507. /// - Parameter completeHander: <#completeHander description#>
  508. /// - Returns: <#description#>
  509. public func pushNotificationIsOpen(completeHander: ((_ isOpen: Bool) -> Void)?) {
  510. if #available(iOS 10.0, *) {
  511. UNUserNotificationCenter.current().getNotificationSettings { setttings in
  512. completeHander!(setttings.authorizationStatus == .authorized)
  513. }
  514. } else {
  515. completeHander!(UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert) ?? false)
  516. }
  517. }
  518. /// 发送上传本地推送
  519. /// - Parameter isSuccess: 是否上传成功
  520. /// - Returns: <#description#>
  521. public func sendUploadNotification(isSuccess: Bool) {
  522. let title: String = isSuccess ? "上传完成了!" : "上传失败了!"
  523. let body: String = isSuccess ? "请点击发布,完成上传。否则,您的视频可能丢失" : "快来看看怎么了?"
  524. sendLocalNotification(title: title, body: body)
  525. }
  526. /// 发送本地推送
  527. /// - Parameters:
  528. /// - title: 标题
  529. /// - body: 内容
  530. /// - Returns: <#description#>
  531. public func sendLocalNotification(title: String, body: String) {
  532. // 设置推送内容
  533. if #available(iOS 10.0, *) {
  534. let content = UNMutableNotificationContent()
  535. content.title = title
  536. content.body = body
  537. content.badge = 1
  538. // 设置通知触发器
  539. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
  540. // 设置请求标识符
  541. let requestIdentifier = getUniqueId(desc: "notification\(title)")
  542. // 设置一个通知请求
  543. let request = UNNotificationRequest(identifier: requestIdentifier,
  544. content: content, trigger: trigger)
  545. // 将通知请求添加到发送中心
  546. UNUserNotificationCenter.current().add(request) { error in
  547. if error == nil {
  548. print("Time Interval Notification scheduled: \(requestIdentifier)")
  549. }
  550. }
  551. } else {
  552. // Fallback on earlier versions
  553. let notification = UILocalNotification()
  554. notification.alertBody = body
  555. notification.alertTitle = title
  556. notification.applicationIconBadgeNumber = 1
  557. notification.fireDate = Date(timeIntervalSinceNow: 0)
  558. UIApplication.shared.scheduledLocalNotifications = [notification]
  559. }
  560. }
  561. /// 打开应用设置
  562. public func openAppSetting() {
  563. if UIApplication.shared.canOpenURL(URL(string: UIApplication.openSettingsURLString)!) {
  564. UIApplication.shared.openURL(URL(string: UIApplication.openSettingsURLString)!)
  565. }
  566. }
  567. /// dns解析
  568. /// - Parameter hostUrl: speed.piaoquantv.com /
  569. /// - Returns: <#description#>
  570. public func parseDNS(hostUrl: String) -> [String: Any]? {
  571. let host: CFHost? = CFHostCreateWithName(nil, hostUrl as CFString).takeRetainedValue()
  572. let start = CFAbsoluteTimeGetCurrent()
  573. var success: DarwinBoolean = false
  574. var addressList: [String] = Array<String>.init()
  575. var addresses: NSArray?
  576. if CFHostStartInfoResolution(host!, .addresses, nil) {
  577. addresses = (CFHostGetAddressing(host!, &success)?.takeUnretainedValue())
  578. }
  579. if success == true {
  580. for case let theAddress as NSData in addresses! {
  581. var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
  582. if getnameinfo(theAddress.bytes.assumingMemoryBound(to: sockaddr.self), socklen_t(theAddress.length),
  583. &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0
  584. {
  585. let numAddress = String(cString: hostname)
  586. addressList.append("\(hostUrl)/\(numAddress)")
  587. }
  588. }
  589. }
  590. let end = CFAbsoluteTimeGetCurrent()
  591. let duration = end - start
  592. BFLog(message: "duration = \(duration)")
  593. BFLog(message: "addressList = \(addressList)")
  594. if addressList.count > 0 {
  595. return ["dnsResult": arrayToJsonString(addressList), "duration": duration * 1000, "hostName": hostUrl, "networkType": networkStatus()]
  596. } else {
  597. return nil
  598. }
  599. }
  600. /// 获取当前日期
  601. /// - Returns: <#description#>
  602. public func systemCurrentDate() -> String {
  603. let dateFormatter = DateFormatter()
  604. dateFormatter.dateFormat = "YYYY-MM-dd"
  605. return dateFormatter.string(from: Date())
  606. }
  607. /// 时间戳转日期
  608. /// - Parameter timeInterval: <#timeInterval description#>
  609. /// - Returns: <#description#>
  610. public func timeIntervalToDateString(timeInterval: TimeInterval) -> String {
  611. let date = Date(timeIntervalSince1970: timeInterval)
  612. let dateFormatter = DateFormatter()
  613. dateFormatter.dateFormat = "yyyy年MM月dd日"
  614. return dateFormatter.string(from: date)
  615. }
  616. public func updateTimeToCurrenTime(timeInterval: TimeInterval) -> String {
  617. // 获取当前的时间戳
  618. let currentTime = Date().timeIntervalSince1970
  619. print(currentTime, timeInterval, "sdsss")
  620. // 时间戳为毫秒级要 / 1000, 秒就不用除1000,参数带没带000
  621. // let timeSta:TimeInterval = TimeInterval(timeInterval / 1000)
  622. // 时间差
  623. let reduceTime: TimeInterval = currentTime - timeInterval
  624. // 时间差小于60秒
  625. if reduceTime < 60 {
  626. return "刚刚"
  627. }
  628. // 时间差大于一分钟小于60分钟内
  629. let mins = Int(reduceTime / 60)
  630. if mins < 60 {
  631. return "\(mins)分钟前"
  632. }
  633. let hours = Int(reduceTime / 3600)
  634. if hours < 24 {
  635. return "\(hours)小时前"
  636. }
  637. // let days = Int(reduceTime / 3600 / 24)
  638. // if days < 30 {
  639. // return "\(days)天前"
  640. // }
  641. // 不满足上述条件---或者是未来日期-----直接返回日期
  642. let date = NSDate(timeIntervalSince1970: timeInterval)
  643. let dfmatter = DateFormatter()
  644. // yyyy-MM-dd HH:mm:ss
  645. dfmatter.dateFormat = "yyyy年M月d日 HH:mm"
  646. var dfmatterStr = dfmatter.string(from: date as Date)
  647. let currentDF = DateFormatter()
  648. // yyyy-MM-dd HH:mm:ss
  649. currentDF.dateFormat = "yyyy"
  650. let currentDFStr = currentDF.string(from: Date())
  651. if dfmatterStr.hasPrefix(currentDFStr) {
  652. dfmatterStr.removeFirst(currentDFStr.count + 1)
  653. }
  654. return dfmatterStr
  655. }
  656. /// 判断字符串或者字典是否为空
  657. /// - Parameter object: <#object description#>
  658. /// - Returns: <#description#>
  659. public func isEmpty(object: Any?) -> Bool {
  660. if object == nil {
  661. return true
  662. }
  663. if object is String {
  664. return (object as! String).count <= 0
  665. }
  666. if object is [String: Any] {
  667. return (object as! [String: Any]).keys.count <= 0
  668. }
  669. return false
  670. }
  671. public func isEmptyObject(object: Any?) -> Bool {
  672. if object == nil {
  673. return true
  674. }
  675. if object is String {
  676. return object == nil || ((object as? String)?.count ?? 0) <= 0
  677. }
  678. if object is [String: Any] {
  679. return object == nil || ((object as? [String: Any])?.keys.count ?? 0) <= 0
  680. }
  681. // if object is List<Object> {
  682. // return object == nil || ((object as? List<Object>)?.count ?? 0) <= 0
  683. // }
  684. return false
  685. }
  686. /// <#Description#>
  687. /// - Parameter string: <#string description#>
  688. /// - Returns: <#description#>
  689. public func isIncludeChineseIn(string: String) -> Bool {
  690. for (_, value) in string.enumerated() {
  691. if value >= "\u{4E00}", value <= "\u{9FA5}" {
  692. return true
  693. }
  694. }
  695. return false
  696. }
  697. /// 获取文件内容的MD5
  698. /// - Parameters:
  699. /// - path: 地址
  700. /// - data: data
  701. /// - Returns: <#description#>
  702. public func contentMD5(path: String? = nil, data _: Data? = nil) -> String? {
  703. if path == nil || (path?.count ?? 0) <= 0 || !FileManager.default.fileExists(atPath: path ?? "") {
  704. BFLog(message: "生成内容md5值:地址错误或者不存在\(String(describing: path))")
  705. return ""
  706. }
  707. let att = try? FileManager.default.attributesOfItem(atPath: path ?? "")
  708. let size = Int64(att?[FileAttributeKey.size] as! UInt64)
  709. if size <= 0 {
  710. BFLog(message: "生成内容md5值:文件大小为0\(size)")
  711. return ""
  712. }
  713. // let hash: String = OSSUtil.base64Md5(forFilePath: path)
  714. let hash: String = ""
  715. BFLog(message: "生成内容md5值:contentMD5 = \(hash)")
  716. return hash
  717. }
  718. /// 自适应宽
  719. /// - Parameters:
  720. /// - width: <#width description#>
  721. /// - baseWidth: <#baseWidth description#>
  722. /// - Returns: <#description#>
  723. public func adapterWidth(width: CGFloat, baseWidth: CGFloat = 375) -> CGFloat {
  724. return width / baseWidth * cScreenWidth
  725. }
  726. /// 自适应高
  727. /// - Parameters:
  728. /// - height: <#height description#>
  729. /// - baseHeight: <#baseHeight description#>
  730. /// - Returns: <#description#>
  731. public func adapterHeight(height: CGFloat, baseHeight: CGFloat = 812) -> CGFloat {
  732. return height / baseHeight * cScreenHeigth
  733. }
  734. /// 检测URL
  735. /// - Parameter url: <#url description#>
  736. /// - Returns: <#description#>
  737. public func isValidURL(url: String?) -> Bool {
  738. if url == nil || (url?.count ?? 0) <= 4 || (!(url?.hasPrefix("http") ?? false) && !(url?.hasPrefix("https") ?? false)) {
  739. return false
  740. }
  741. return true
  742. }
  743. /// 相册数据按创建时间排序
  744. public var creaFetchOptions: PHFetchOptions = {
  745. let fetchOptions = PHFetchOptions()
  746. fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
  747. return fetchOptions
  748. }()
  749. /// 相册数据按修改时间排序
  750. public var modiFetchOptions: PHFetchOptions = {
  751. let fetchOptions = PHFetchOptions()
  752. fetchOptions.sortDescriptors = [NSSortDescriptor(key: "modificationDate", ascending: false)]
  753. return fetchOptions
  754. }()
  755. /// 获取本地素材
  756. public var avAssertOptions: [String: Any]? = {
  757. [AVURLAssetPreferPreciseDurationAndTimingKey: NSNumber(value: true)]
  758. }()
  759. /// 播放动画图
  760. public var playGifImages: [UIImage] = {
  761. var gifImages = Array<UIImage>.init()
  762. for i in 0 ... 44 {
  763. gifImages.append(UIImage(named: "\(i).png")!)
  764. }
  765. return gifImages
  766. }()
  767. /// 压缩图片
  768. /// - Parameter image: <#image description#>
  769. /// -
  770. /// - Returns: <#description#>
  771. public func zipImage(image: UIImage?, size: Int) -> Data? {
  772. var data = image?.pngData()
  773. var dataKBytes = Int(data?.count ?? 0) / 1000
  774. var maxQuality = 0.9
  775. while dataKBytes > size, maxQuality > 0.01 {
  776. maxQuality = maxQuality - 0.01
  777. data = image?.jpegData(compressionQuality: CGFloat(maxQuality))
  778. dataKBytes = (data?.count ?? 0) / 1000
  779. }
  780. return data
  781. }
  782. /// 压缩图片到指定大小
  783. /// - Parameters:
  784. /// - image: <#image description#>
  785. /// - maxLength: <#maxLength description#>
  786. /// - cyles: <#cyles description#>
  787. /// - Returns: <#description#>
  788. public func zipImageQuality(image: UIImage, maxLength: NSInteger, cyles: Int = 6) -> Data {
  789. var compression: CGFloat = 1
  790. var data = image.jpegData(compressionQuality: compression)!
  791. if data.count < maxLength {
  792. return data
  793. }
  794. var max: CGFloat = 1
  795. var min: CGFloat = 0
  796. var bestData: Data = data
  797. for _ in 0 ..< cyles {
  798. compression = (max + min) / 2
  799. data = image.jpegData(compressionQuality: compression)!
  800. if Double(data.count) < Double(maxLength) * 0.9 {
  801. min = compression
  802. bestData = data
  803. } else if data.count > maxLength {
  804. max = compression
  805. } else {
  806. bestData = data
  807. break
  808. }
  809. }
  810. return bestData
  811. }
  812. public func resetImgSize(sourceImage: UIImage, maxImageLenght: CGFloat, maxSizeKB: CGFloat) -> Data {
  813. var maxSize = maxSizeKB
  814. var maxImageSize = maxImageLenght
  815. if maxSize <= 0.0 {
  816. maxSize = 1024.0
  817. }
  818. if maxImageSize <= 0.0 {
  819. maxImageSize = 1024.0
  820. }
  821. // 先调整分辨率
  822. var newSize = CGSize(width: sourceImage.size.width, height: sourceImage.size.height)
  823. let tempHeight = newSize.height / maxImageSize
  824. let tempWidth = newSize.width / maxImageSize
  825. if tempWidth > 1.0, tempWidth > tempHeight {
  826. newSize = CGSize(width: sourceImage.size.width / tempWidth, height: sourceImage.size.height / tempWidth)
  827. } else if tempHeight > 1.0, tempWidth < tempHeight {
  828. newSize = CGSize(width: sourceImage.size.width / tempHeight, height: sourceImage.size.height / tempHeight)
  829. }
  830. UIGraphicsBeginImageContext(newSize)
  831. sourceImage.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  832. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  833. UIGraphicsEndImageContext()
  834. var imageData = newImage!.jpegData(compressionQuality: 1.0)
  835. var sizeOriginKB: CGFloat = CGFloat((imageData?.count)!) / 1024.0
  836. // 调整大小
  837. var resizeRate = 0.9
  838. while sizeOriginKB > maxSize, resizeRate > 0.1 {
  839. imageData = newImage!.jpegData(compressionQuality: CGFloat(resizeRate))
  840. sizeOriginKB = CGFloat((imageData?.count)!) / 1024.0
  841. resizeRate -= 0.1
  842. }
  843. return imageData!
  844. }
  845. /// 获取开屏广告图
  846. /// - Returns: <#description#>
  847. public func getLaunchImage() -> UIImage {
  848. var lauchImg: UIImage!
  849. var viewOrientation: String!
  850. let viewSize = UIScreen.main.bounds.size
  851. let orientation = UIApplication.shared.statusBarOrientation
  852. if orientation == .landscapeLeft || orientation == .landscapeRight {
  853. viewOrientation = "Landscape"
  854. } else {
  855. viewOrientation = "Portrait"
  856. }
  857. let imgsInfoArray = Bundle.main.infoDictionary!["UILaunchImages"]
  858. for dict: [String: String] in imgsInfoArray as! Array {
  859. let imageSize = NSCoder.cgSize(for: dict["UILaunchImageSize"]!)
  860. if __CGSizeEqualToSize(imageSize, viewSize), viewOrientation == dict["UILaunchImageOrientation"]! as String {
  861. lauchImg = UIImage(named: dict["UILaunchImageName"]!)
  862. }
  863. }
  864. return lauchImg
  865. }