PQCommonMethodUtil.swift 35 KB

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