PQCommonMethodUtil.swift 33 KB

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