KMAdvertisementManager.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. //
  2. // KMAdvertisementManager.swift
  3. // KMAdvertisement
  4. //
  5. // Created by lizhe on 2022/11/23.
  6. // 广告管理
  7. @objcMembers open class KMAdvertisementManager: NSObject {
  8. //单例
  9. @objc public static let manager = KMAdvertisementManager()
  10. @objc public var configuration: KMAdvertisementConfig = KMAdvertisementConfig()
  11. /**
  12. @abstract 测试模式,默认为false
  13. */
  14. @objc public var debug: Bool = false
  15. /**
  16. @abstract 初始化数据
  17. @param appID 产品名称
  18. @param subscribeType 订阅状态,可单独在configuration设置
  19. @param platform 平台
  20. @return
  21. */
  22. @objc public func initConfig(appName: KMAdvertisementAppNameType,
  23. subscribeType:KMAdvertisementSubscribeType,
  24. platform: KMAdvertisementPlatformType) {
  25. configuration.initParameters(appName: appName, subscribeType: subscribeType, platform: platform)
  26. }
  27. private class InternalImplementation {
  28. fileprivate var privateProperty: String = "Hidden"
  29. fileprivate func internalMethod() {
  30. // 实现细节
  31. }
  32. }
  33. private let internalImplementation = InternalImplementation()
  34. public func publicMethod() {
  35. // 使用内部实现
  36. internalImplementation.internalMethod()
  37. }
  38. }
  39. extension KMAdvertisementManager {
  40. //MARK: request
  41. /**
  42. @abstract 获取数据
  43. @param data 传入参数 类型为KMAdvertisementModel
  44. @return
  45. */
  46. @objc public func fetchData(completion: @escaping (_ data: KMAdvertisementInfo?, _ error:Error?) -> Void) -> Void {
  47. self.fetchDataWithResponseObject { data, responseObject, error in
  48. if completion != nil {
  49. completion(data, error)
  50. }
  51. }
  52. }
  53. @objc public func fetchDataWithResponseObject(completion:@escaping (_ data: KMAdvertisementInfo?, _ responseObject: AnyObject? , _ error:Error?) -> Void) -> Void {
  54. print("开始获取数据")
  55. var version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString").debugDescription
  56. if (version.count == 0) {
  57. version = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion").debugDescription
  58. version = version.replacingOccurrences(of: ".", with: "")
  59. }
  60. let urlString = configuration.activityBaseURL() + "/api/advertise-new"
  61. let params: [String:Any] = ["app_name": configuration.appName.string(),
  62. "app_version": version]
  63. //先拿缓存数据 再请求新数据
  64. let cacheData = KMAdvertisementCache.default.readData()
  65. if cacheData.count != 0 {
  66. self.parseData(data: cacheData, isNeedLocalComparison: false) { result in
  67. if result.count != 0 {
  68. completion(result.first, nil, nil)
  69. }
  70. }
  71. }
  72. unowned let weakSelf = self
  73. KMAdvertisementRequestServer.requestServer.request(urlString: urlString, method: "GET", params: params) { task, responseObject, error in
  74. print("正在获取数据")
  75. if (error == nil && responseObject != nil) {
  76. let array = responseObject?["list"] ?? []
  77. if array != nil {
  78. //解析数据
  79. print("开始解析数据")
  80. weakSelf.parseData(data: array as! [NSDictionary], isNeedLocalComparison: true) { data in
  81. print("数据处理完毕")
  82. if data.count != 0 {
  83. completion(data.first, responseObject, nil)
  84. }
  85. }
  86. } else {
  87. print("解析数据失败array")
  88. completion(nil, responseObject, error)
  89. }
  90. } else {
  91. print("解析数据失败数据不存在")
  92. completion(nil, responseObject, error)
  93. }
  94. }
  95. }
  96. }
  97. extension KMAdvertisementManager {
  98. //MARK: data
  99. /**
  100. @abstract 解析数据
  101. @param data 传入参数 NSDictionary
  102. @param isNeedLocalComparison 是否需要对比本地版本,如果不一样将会刷新
  103. @return KMAdvertisementModel
  104. */
  105. public func parseData(data: [NSDictionary], isNeedLocalComparison: Bool ,completion:(_ result: [KMAdvertisementInfo]) -> Void) -> Void {
  106. //获取缓存数据
  107. var isNeedSave = false
  108. let cacheData = KMAdvertisementCache.default.readData()
  109. var resultArray:[KMAdvertisementInfo] = []
  110. for model in data {
  111. if (!(cacheData.contains(model) && isNeedLocalComparison)) {
  112. if (self.allowLoadData(data: model)) {
  113. let jsonString: String = (model["detail"] as? String) ?? ""
  114. let jsonData: Data = jsonString.data(using: .utf8)!
  115. let dict = try?JSONSerialization.jsonObject(with: jsonData)
  116. let decoder = JSONDecoder()
  117. // decoder.dataDecodingStrategy = .base64
  118. // decoder.keyDecodingStrategy = .convertFromSnakeCase //带下划线命名
  119. decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+∞", negativeInfinity: "-∞", nan: "NaN")
  120. #if DEBUG
  121. //MARK: 测试使用
  122. var advertisementModel = try! decoder.decode(KMAdvertisementInfo.self, from: jsonData)
  123. if (self.allowLoadContentData(data: advertisementModel)) {
  124. resultArray.append(self.allowLoadItemData(advertisementModel))
  125. isNeedSave = true
  126. }
  127. #else
  128. // MARK: 此处try 使用 ? ,如果数据出问题 advertisementModel将无参数, 测试时使用!
  129. var advertisementModel = try? decoder.decode(KMAdvertisementModel.self, from: jsonData)
  130. if (advertisementModel != nil) {
  131. if (self.allowLoadContentData(data: advertisementModel!)) {
  132. resultArray.append(self.allowLoadItemData(advertisementModel!))
  133. isNeedSave = true
  134. }
  135. }
  136. #endif
  137. }
  138. }
  139. }
  140. if isNeedSave && isNeedLocalComparison {
  141. KMAdvertisementCache.default.saveData(data: data)
  142. print("已更新本地数据")
  143. } else {
  144. print("不需要更新本地数据")
  145. }
  146. completion(resultArray)
  147. }
  148. func allowLoadData(data: NSDictionary) -> Bool {
  149. var result = false
  150. let status = (data["status"] as? Int) ?? 0
  151. let app_name: String = data["app_name"] as? String ?? ""
  152. if (status == 1 &&
  153. app_name == configuration.appName.string()) {
  154. result = true
  155. }
  156. return result
  157. }
  158. func allowLoadContentData(data: KMAdvertisementInfo) -> Bool {
  159. var result = true
  160. return result
  161. }
  162. // func allowLoadContentData(data: KMAdvertisementModel) -> Bool {
  163. // var result = false
  164. //
  165. // let time: NSInteger = NSInteger(KMAdvertisementTimeStampConversion.getCurrentTimeInterval())!
  166. // let startTime: NSInteger = NSInteger(data.startTime!)!
  167. // let endTime: NSInteger = NSInteger(data.endTime!)!
  168. // let platform = configuration.platform
  169. // let subscribeType = configuration.subscribeType
  170. // let version = data.version ?? "1.0"
  171. // let localVersion = self.getLocalVersion()
  172. // let hidden = data.hidden ?? false
  173. //
  174. // if (time >= startTime &&
  175. // time <= endTime &&
  176. // platform == data.platform &&
  177. // self.compareVersion(nowVersion:localVersion, newVersion: version) &&
  178. // (subscribeType == data.subscribeType || data.subscribeType == .all) &&
  179. // !hidden) {
  180. // result = true
  181. // }
  182. // return result
  183. // }
  184. //过滤item是否显示
  185. func allowLoadItemData(_ data: KMAdvertisementInfo) -> KMAdvertisementInfo {
  186. return data;
  187. }
  188. // func allowLoadItemData(_ data: KMAdvertisementModel) -> KMAdvertisementModel {
  189. // //获取缓存数据
  190. // if (UserDefaults.standard.object(forKey: "KMAdvertisementShowScroll_iOS") == nil) {
  191. // UserDefaults.standard.set([], forKey: "KMAdvertisementShowScroll_iOS")
  192. // }
  193. // let cacheArray: [String] = UserDefaults.standard.object(forKey: "KMAdvertisementShowScroll_iOS") as! [String]
  194. //
  195. // let model = data
  196. // var sections: [KMAdvertisementModelSection] = []
  197. // for section in data.content! {
  198. // var items: [KMAdvertisementModelItem] = []
  199. // for item in section.content! {
  200. // let timeString = KMAdvertisementTimeStampConversion.getCurrentTimeInterval()
  201. // let time: NSInteger = NSInteger(timeString)!
  202. // let startTime: NSInteger = NSInteger(item.startTime ?? timeString)!
  203. // let endTime: NSInteger = NSInteger(item.endTime ?? timeString)!
  204. // let hidden = item.hidden ?? false
  205. //
  206. //// print(hidden ? "隐藏" : "显示")
  207. // if (!hidden &&
  208. // time >= startTime &&
  209. // time <= endTime &&
  210. // !cacheArray.contains(item.productID ?? "")) {
  211. // items.append(item)
  212. // }
  213. // }
  214. // section.content = items
  215. // sections.append(section)
  216. // }
  217. // model.content = sections
  218. // return model
  219. // }
  220. //获取本地版本号
  221. func getLocalVersion() -> String {
  222. var localVersion = ""
  223. if let v: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
  224. localVersion = v
  225. }
  226. return localVersion
  227. }
  228. func compareVersion(nowVersion: String, newVersion: String) -> Bool {
  229. let nowArray = nowVersion.split(separator: ".")
  230. let newArray = newVersion.split(separator: ".")
  231. let big = nowArray.count > newArray.count ? newArray.count : nowArray.count
  232. if big != 0 {
  233. for index in 0...big - 1 {
  234. let first = nowArray[index]
  235. let second = newArray[index]
  236. if Int(first)! < Int(second)! {
  237. return true
  238. }
  239. if index == big - 1 {
  240. if Int(first)! <= Int(second)! {
  241. return true
  242. }
  243. }
  244. }
  245. } else {
  246. return true
  247. }
  248. return false
  249. }
  250. }