PQCommonMethodUtil.swift 29 KB

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