PQCommonMethodUtil.swift 29 KB

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