PQCommonMethodUtil.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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>(_ message:T,file:String = #file,funcName:String = #function,lineNum:Int = #line){
  134. #if DEBUG
  135. let file = (file as NSString).lastPathComponent;
  136. print("hhz-\(file):(\(lineNum))--\(message)");
  137. #endif
  138. }
  139. // MARK: 获取公共参数
  140. public func commonParams() -> [String: Any] {
  141. let model = UIDevice.current.model
  142. let systemName = UIDevice.current.systemName
  143. let systemVersion = UIDevice.current.systemVersion
  144. let localizedModel = UIDevice.current.localizedModel
  145. let machineInfo: [String: Any] = [
  146. "model": model, "system": systemName + " " + systemVersion, "brand": localizedModel, "platform": "iOS", "networkType": networkStatus(), "clientIp": ipAddress(),
  147. ]
  148. var commParams: [String: Any] = [
  149. "appVersionCode": versionCode,
  150. "versionCode": versionCode,
  151. "system": systemName + " " + systemVersion,
  152. "systemVersion": systemName + " " + systemVersion,
  153. "appType": PQBFConfig.shared.appType,
  154. "appId": PQBFConfig.shared.appId,
  155. "machineCode": getMachineCode(),
  156. "networkType": networkStatus(),
  157. "ipAddress": ipAddress(),
  158. "clientTimestamp": Int64(Date().timeIntervalSince1970 * 1000),
  159. "platform": "iOS",
  160. "versionName": versionName,
  161. "mid": getMachineCode(),
  162. "machineInfo": dictionaryToJsonString(machineInfo) ?? "",
  163. "requestId": getUniqueId(desc: "requestId"),
  164. "idfa": ASIdentifierManager.shared().advertisingIdentifier.uuidString,
  165. "idfv": UIDevice.current.identifierForVendor?.uuidString ?? "",
  166. "sessionId": PQBFConfig.shared.sessionId,
  167. "subSessionId": PQBFConfig.shared.subSessionId ?? PQBFConfig.shared.sessionId,
  168. ]
  169. if PQBFConfig.shared.token != nil, (PQBFConfig.shared.token?.count ?? 0) > 0 {
  170. commParams["token"] = PQBFConfig.shared.token ?? ""
  171. }
  172. if PQBFConfig.shared.loginUid != nil, (PQBFConfig.shared.loginUid?.count ?? 0) > 0 {
  173. commParams["loginUid"] = PQBFConfig.shared.loginUid ?? ""
  174. commParams["uid"] = PQBFConfig.shared.loginUid ?? ""
  175. }
  176. if PQBFConfig.shared.deviceToken != nil, (PQBFConfig.shared.deviceToken?.count ?? 0) > 0 {
  177. commParams["deviceToken"] = PQBFConfig.shared.deviceToken ?? ""
  178. }
  179. return commParams
  180. }
  181. /// 获取网络状态
  182. /// - Returns: <#description#>
  183. public func networkStatus() -> String {
  184. let status = NetworkReachabilityManager(host: "www.baidu.com")?.status
  185. var statusStr: String!
  186. switch status {
  187. case .unknown:
  188. statusStr = "NETWORK_UNKNOWN"
  189. case .notReachable:
  190. statusStr = "NETWORK_NO"
  191. case .reachable(.cellular):
  192. statusStr = "4G/5G"
  193. case .reachable(.ethernetOrWiFi):
  194. statusStr = "Wi-Fi"
  195. default:
  196. statusStr = "NETWORK_UNKNOWN"
  197. }
  198. return statusStr
  199. }
  200. /// 判断是否有网
  201. /// - Returns: <#description#>
  202. public func isNetConnected() -> Bool {
  203. return NetworkReachabilityManager(host: "www.baidu.com")?.status == .reachable(.cellular) || NetworkReachabilityManager(host: "www.baidu.com")?.status == .reachable(.ethernetOrWiFi)
  204. }
  205. /// 获取ip地址
  206. /// - Returns: <#description#>
  207. public func ipAddress() -> String {
  208. var addresses = [String]()
  209. var ifaddr: UnsafeMutablePointer<ifaddrs>?
  210. if getifaddrs(&ifaddr) == 0 {
  211. var ptr = ifaddr
  212. while ptr != nil {
  213. let flags = Int32(ptr!.pointee.ifa_flags)
  214. var addr = ptr!.pointee.ifa_addr.pointee
  215. if (flags & (IFF_UP | IFF_RUNNING | IFF_LOOPBACK)) == (IFF_UP | IFF_RUNNING) {
  216. if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) {
  217. var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
  218. if getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0 {
  219. if let address = String(validatingUTF8: hostname) {
  220. addresses.append(address)
  221. }
  222. }
  223. }
  224. }
  225. ptr = ptr!.pointee.ifa_next
  226. }
  227. freeifaddrs(ifaddr)
  228. }
  229. return addresses.first ?? "0.0.0.0"
  230. }
  231. /// 生成唯一ID / 分享跟冷启动
  232. /// - Parameter desc: <#desc description#>
  233. /// - Returns: <#description#>
  234. public func getUniqueId(desc: String) -> String {
  235. let timeStr: String = "\(Date().timeIntervalSince1970)"
  236. let uuid: String = getMachineCode()
  237. let code: String = "\(arc4random_uniform(1_000_000_000))"
  238. let uniqueId = (timeStr + desc + uuid + code).md5.md5
  239. BFLog(message: "生成唯一码:desc = \(desc),timeStr = \(timeStr),uuid = \(uuid),code = \(code),uniqueId = \(uniqueId)")
  240. return uniqueId
  241. }
  242. // MARK: 字典转字符串
  243. public func dictionaryToJsonString(_ dic: [String: Any]) -> String? {
  244. BFLog(message: "dictionaryToJsonString = \(dic)")
  245. if !JSONSerialization.isValidJSONObject(dic) {
  246. return ""
  247. }
  248. guard let data = try? JSONSerialization.data(withJSONObject: dic, options: []) else {
  249. return ""
  250. }
  251. BFLog(message: "dictionaryToJsonString - data = \(data)")
  252. let str = String(data: data, encoding: String.Encoding.utf8)
  253. BFLog(message: "dictionaryToJsonString - str = \(String(describing: str))")
  254. return str
  255. }
  256. // MARK: 字符串转字典
  257. public func jsonStringToDictionary(_ str: String) -> [String: Any]? {
  258. if str.count <= 0 {
  259. return [:]
  260. }
  261. let data = str.data(using: String.Encoding.utf8)
  262. if data == nil || (data?.count ?? 0) <= 0 {
  263. return [:]
  264. }
  265. if let dict = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any] {
  266. return dict
  267. }
  268. return [:]
  269. }
  270. // MARK: 字符串转数组
  271. public func jsonStringToArray(_ str: String) -> [[String: String]]? {
  272. let data = str.data(using: String.Encoding.utf8)
  273. if let array = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [[String: String]] {
  274. return array
  275. }
  276. return nil
  277. }
  278. /// 数组转为string
  279. /// - Parameter array: <#array description#>
  280. /// - Returns: <#description#>
  281. public func arrayToJsonString(_ array: [Any]) -> String {
  282. if !JSONSerialization.isValidJSONObject(array) {
  283. BFLog(message: "无法解析String")
  284. return ""
  285. }
  286. let data: NSData! = try? JSONSerialization.data(withJSONObject: array, options: []) as NSData?
  287. let JSONString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue)
  288. return JSONString! as String
  289. }
  290. /// jsonString转为数组
  291. /// - Parameter jsonString: <#jsonString description#>
  292. /// - Returns: <#description#>
  293. public func jsonStringToArray(jsonString: String) -> [Any]? {
  294. let data = jsonString.data(using: String.Encoding.utf8)
  295. if data == nil {
  296. return nil
  297. }
  298. if let array = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [Any] {
  299. return array
  300. }
  301. return nil
  302. }
  303. /// 计算字符串大小
  304. /// - Parameters:
  305. /// - text: <#text description#>
  306. /// - font: <#font description#>
  307. /// - size: <#size description#>
  308. /// - Returns: <#description#>
  309. public func sizeWithText(attributedText: NSMutableAttributedString? = nil, text: String, font: UIFont, size: CGSize) -> CGSize {
  310. let option = NSStringDrawingOptions.usesLineFragmentOrigin
  311. if attributedText != nil {
  312. let rect: CGRect = attributedText?.boundingRect(with: size, options: option, context: nil) ?? CGRect(origin: CGPoint.zero, size: size)
  313. return rect.size
  314. } else {
  315. let attributes = [NSAttributedString.Key.font: font]
  316. let rect: CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil)
  317. return rect.size
  318. }
  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 = "yyyy年MM月dd日"
  615. return dateFormatter.string(from: date)
  616. }
  617. public func updateTimeToCurrenTime(timeInterval: TimeInterval) -> String {
  618. //获取当前的时间戳
  619. let currentTime = Date().timeIntervalSince1970
  620. // print(currentTime, timeInterval, "sdsss")
  621. //时间戳为毫秒级要 / 1000, 秒就不用除1000,参数带没带000
  622. // let timeSta:TimeInterval = TimeInterval(timeInterval / 1000)
  623. // 时间差
  624. let reduceTime: TimeInterval = currentTime - timeInterval
  625. // 时间差小于60秒
  626. if reduceTime < 60 {
  627. return "刚刚"
  628. }
  629. // 时间差大于一分钟小于60分钟内
  630. let mins = Int(reduceTime / 60)
  631. if mins < 60 {
  632. return "\(mins)分钟前"
  633. }
  634. let hours = Int(reduceTime / 3600)
  635. if hours < 24 {
  636. return "\(hours)小时前"
  637. }
  638. // let days = Int(reduceTime / 3600 / 24)
  639. // if days < 30 {
  640. // return "\(days)天前"
  641. // }
  642. // 不满足上述条件---或者是未来日期-----直接返回日期
  643. let date = NSDate(timeIntervalSince1970: timeInterval)
  644. let dfmatter = DateFormatter()
  645. // yyyy-MM-dd HH:mm:ss
  646. dfmatter.dateFormat = "yyyy年M月d日 HH:mm"
  647. var dfmatterStr = dfmatter.string(from: date as Date)
  648. let currentDF = DateFormatter()
  649. // yyyy-MM-dd HH:mm:ss
  650. currentDF.dateFormat = "yyyy"
  651. let currentDFStr = currentDF.string(from: Date())
  652. if dfmatterStr.hasPrefix(currentDFStr) {
  653. dfmatterStr.removeFirst(currentDFStr.count + 1)
  654. }
  655. return dfmatterStr
  656. }
  657. /// 判断字符串或者字典是否为空
  658. /// - Parameter object: <#object description#>
  659. /// - Returns: <#description#>
  660. public func isEmpty(object: Any?) -> Bool {
  661. if object == nil {
  662. return true
  663. }
  664. if object is String {
  665. return (object as! String).count <= 0
  666. }
  667. if object is [String: Any] {
  668. return (object as! [String: Any]).keys.count <= 0
  669. }
  670. return false
  671. }
  672. public func isEmptyObject(object: Any?) -> Bool {
  673. if object == nil {
  674. return true
  675. }
  676. if object is String {
  677. return object == nil || ((object as? String)?.count ?? 0) <= 0
  678. }
  679. if object is [String: Any] {
  680. return object == nil || ((object as? [String: Any])?.keys.count ?? 0) <= 0
  681. }
  682. // if object is List<Object> {
  683. // return object == nil || ((object as? List<Object>)?.count ?? 0) <= 0
  684. // }
  685. return false
  686. }
  687. /// <#Description#>
  688. /// - Parameter string: <#string description#>
  689. /// - Returns: <#description#>
  690. public func isIncludeChineseIn(string: String) -> Bool {
  691. for (_, value) in string.enumerated() {
  692. if value >= "\u{4E00}", value <= "\u{9FA5}" {
  693. return true
  694. }
  695. }
  696. return false
  697. }
  698. /// 获取文件内容的MD5
  699. /// - Parameters:
  700. /// - path: 地址
  701. /// - data: data
  702. /// - Returns: <#description#>
  703. public func contentMD5(path: String? = nil, data _: Data? = nil) -> String? {
  704. if path == nil || (path?.count ?? 0) <= 0 || !FileManager.default.fileExists(atPath: path ?? "") {
  705. BFLog(message: "生成内容md5值:地址错误或者不存在\(String(describing: path))")
  706. return ""
  707. }
  708. let att = try? FileManager.default.attributesOfItem(atPath: path ?? "")
  709. let size = Int64(att?[FileAttributeKey.size] as! UInt64)
  710. if size <= 0 {
  711. BFLog(message: "生成内容md5值:文件大小为0\(size)")
  712. return ""
  713. }
  714. // let hash: String = OSSUtil.base64Md5(forFilePath: path)
  715. let hash: String = ""
  716. BFLog(message: "生成内容md5值:contentMD5 = \(hash)")
  717. return hash
  718. }
  719. /// 自适应宽
  720. /// - Parameters:
  721. /// - width: <#width description#>
  722. /// - baseWidth: <#baseWidth description#>
  723. /// - Returns: <#description#>
  724. public func adapterWidth(width: CGFloat, baseWidth: CGFloat = 375) -> CGFloat {
  725. return width / baseWidth * cScreenWidth
  726. }
  727. /// 自适应高
  728. /// - Parameters:
  729. /// - height: <#height description#>
  730. /// - baseHeight: <#baseHeight description#>
  731. /// - Returns: <#description#>
  732. public func adapterHeight(height: CGFloat, baseHeight: CGFloat = 812) -> CGFloat {
  733. return height / baseHeight * cScreenHeigth
  734. }
  735. /// 检测URL
  736. /// - Parameter url: <#url description#>
  737. /// - Returns: <#description#>
  738. public func isValidURL(url: String?) -> Bool {
  739. if url == nil || (url?.count ?? 0) <= 4 || (!(url?.hasPrefix("http") ?? false) && !(url?.hasPrefix("https") ?? false)) {
  740. return false
  741. }
  742. return true
  743. }
  744. /// 相册数据按创建时间排序
  745. public var creaFetchOptions: PHFetchOptions = {
  746. let fetchOptions = PHFetchOptions()
  747. fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
  748. return fetchOptions
  749. }()
  750. /// 相册数据按修改时间排序
  751. public var modiFetchOptions: PHFetchOptions = {
  752. let fetchOptions = PHFetchOptions()
  753. fetchOptions.sortDescriptors = [NSSortDescriptor(key: "modificationDate", ascending: false)]
  754. return fetchOptions
  755. }()
  756. /// 获取本地素材
  757. public var avAssertOptions: [String: Any]? = {
  758. [AVURLAssetPreferPreciseDurationAndTimingKey: NSNumber(value: true)]
  759. }()
  760. /// 播放动画图
  761. public var playGifImages: [UIImage] = {
  762. var gifImages = Array<UIImage>.init()
  763. for i in 0 ... 44 {
  764. gifImages.append(UIImage(named: "\(i).png")!)
  765. }
  766. return gifImages
  767. }()
  768. /// 压缩图片
  769. /// - Parameter image: <#image description#>
  770. /// -
  771. /// - Returns: <#description#>
  772. public func zipImage(image: UIImage?, size: Int) -> Data? {
  773. var data = image?.pngData()
  774. var dataKBytes = Int(data?.count ?? 0) / 1000
  775. var maxQuality = 0.9
  776. while dataKBytes > size, maxQuality > 0.01 {
  777. maxQuality = maxQuality - 0.01
  778. data = image?.jpegData(compressionQuality: CGFloat(maxQuality))
  779. dataKBytes = (data?.count ?? 0) / 1000
  780. }
  781. return data
  782. }
  783. /// 压缩图片到指定大小
  784. /// - Parameters:
  785. /// - image: <#image description#>
  786. /// - maxLength: <#maxLength description#>
  787. /// - cyles: <#cyles description#>
  788. /// - Returns: <#description#>
  789. public func zipImageQuality(image: UIImage, maxLength: NSInteger, cyles: Int = 6) -> Data {
  790. var compression: CGFloat = 1
  791. var data = image.jpegData(compressionQuality: compression)!
  792. if data.count < maxLength {
  793. return data
  794. }
  795. var max: CGFloat = 1
  796. var min: CGFloat = 0
  797. var bestData: Data = data
  798. for _ in 0 ..< cyles {
  799. compression = (max + min) / 2
  800. data = image.jpegData(compressionQuality: compression)!
  801. if Double(data.count) < Double(maxLength) * 0.9 {
  802. min = compression
  803. bestData = data
  804. } else if data.count > maxLength {
  805. max = compression
  806. } else {
  807. bestData = data
  808. break
  809. }
  810. }
  811. return bestData
  812. }
  813. public func resetImgSize(sourceImage: UIImage, maxImageLenght: CGFloat, maxSizeKB: CGFloat) -> Data {
  814. var maxSize = maxSizeKB
  815. var maxImageSize = maxImageLenght
  816. if maxSize <= 0.0 {
  817. maxSize = 1024.0
  818. }
  819. if maxImageSize <= 0.0 {
  820. maxImageSize = 1024.0
  821. }
  822. // 先调整分辨率
  823. var newSize = CGSize(width: sourceImage.size.width, height: sourceImage.size.height)
  824. let tempHeight = newSize.height / maxImageSize
  825. let tempWidth = newSize.width / maxImageSize
  826. if tempWidth > 1.0, tempWidth > tempHeight {
  827. newSize = CGSize(width: sourceImage.size.width / tempWidth, height: sourceImage.size.height / tempWidth)
  828. } else if tempHeight > 1.0, tempWidth < tempHeight {
  829. newSize = CGSize(width: sourceImage.size.width / tempHeight, height: sourceImage.size.height / tempHeight)
  830. }
  831. UIGraphicsBeginImageContext(newSize)
  832. sourceImage.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  833. let newImage = UIGraphicsGetImageFromCurrentImageContext()
  834. UIGraphicsEndImageContext()
  835. var imageData = newImage!.jpegData(compressionQuality: 1.0)
  836. var sizeOriginKB: CGFloat = CGFloat((imageData?.count)!) / 1024.0
  837. // 调整大小
  838. var resizeRate = 0.9
  839. while sizeOriginKB > maxSize, resizeRate > 0.1 {
  840. imageData = newImage!.jpegData(compressionQuality: CGFloat(resizeRate))
  841. sizeOriginKB = CGFloat((imageData?.count)!) / 1024.0
  842. resizeRate -= 0.1
  843. }
  844. return imageData!
  845. }
  846. /// 获取开屏广告图
  847. /// - Returns: <#description#>
  848. public func getLaunchImage() -> UIImage {
  849. var lauchImg: UIImage!
  850. var viewOrientation: String!
  851. let viewSize = UIScreen.main.bounds.size
  852. let orientation = UIApplication.shared.statusBarOrientation
  853. if orientation == .landscapeLeft || orientation == .landscapeRight {
  854. viewOrientation = "Landscape"
  855. } else {
  856. viewOrientation = "Portrait"
  857. }
  858. let imgsInfoArray = Bundle.main.infoDictionary!["UILaunchImages"]
  859. for dict: [String: String] in imgsInfoArray as! Array {
  860. let imageSize = NSCoder.cgSize(for: dict["UILaunchImageSize"]!)
  861. if __CGSizeEqualToSize(imageSize, viewSize), viewOrientation == dict["UILaunchImageOrientation"]! as String {
  862. lauchImg = UIImage(named: dict["UILaunchImageName"]!)
  863. }
  864. }
  865. return lauchImg
  866. }