KMAdvertisementManager.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. var info: KMAdvertisementInfo = KMAdvertisementInfo()
  12. var infoDict: NSDictionary = NSDictionary()
  13. /**
  14. @abstract 测试模式,默认为false
  15. */
  16. @objc public var debug: Bool = false
  17. /**
  18. @abstract 初始化数据
  19. @param appID 产品名称
  20. @param subscribeType 订阅状态,可单独在configuration设置
  21. @param platform 平台
  22. @return
  23. */
  24. @objc public func initConfig(appName: KMAdvertisementAppNameType,
  25. subscribeType:KMAdvertisementSubscribeType,
  26. platform: KMAdvertisementPlatformType) {
  27. configuration.initParameters(appName: appName, subscribeType: subscribeType, platform: platform)
  28. }
  29. private class InternalImplementation {
  30. fileprivate var privateProperty: String = "Hidden"
  31. fileprivate func internalMethod() {
  32. // 实现细节
  33. }
  34. }
  35. private let internalImplementation = InternalImplementation()
  36. public func publicMethod() {
  37. // 使用内部实现
  38. internalImplementation.internalMethod()
  39. }
  40. }
  41. extension KMAdvertisementManager {
  42. //MARK: request
  43. /**
  44. @abstract 获取数据
  45. @param data 传入参数 类型为KMAdvertisementModel
  46. @return
  47. */
  48. @objc public func fetchData(completion: @escaping (_ data: KMAdvertisementInfo?, _ error:Error?) -> Void) -> Void {
  49. self.fetchDataWithResponseObject { data, responseObject, error in
  50. if completion != nil {
  51. completion(data, error)
  52. }
  53. }
  54. }
  55. @objc public func fetchDataWithResponseObject(completion:@escaping (_ data: KMAdvertisementInfo?, _ responseObject: AnyObject? , _ error:Error?) -> Void) -> Void {
  56. print("开始获取数据")
  57. var version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString").debugDescription
  58. if (version.count == 0) {
  59. version = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion").debugDescription
  60. version = version.replacingOccurrences(of: ".", with: "")
  61. }
  62. let urlString = configuration.activityBaseURL() + "/api/advertise-new"
  63. let params: [String:Any] = ["app_name": configuration.appName.string(),
  64. "app_version": version]
  65. //先拿缓存数据 再请求新数据
  66. let cacheData = KMAdvertisementCache.default.readData()
  67. if cacheData.count != 0 {
  68. for model in cacheData {
  69. let jsonString: String = (model["detail"] as? String) ?? ""
  70. let jsonData: Data = jsonString.data(using: .utf8)!
  71. let dict = try?JSONSerialization.jsonObject(with: jsonData)
  72. infoDict = dict as! NSDictionary
  73. }
  74. self.parseData(data: cacheData, isNeedLocalComparison: false) { result in
  75. if result.count != 0 {
  76. info = result.first!
  77. completion(result.first, nil, nil)
  78. }
  79. }
  80. }
  81. unowned let weakSelf = self
  82. KMAdvertisementRequestServer.requestServer.request(urlString: urlString, method: "GET", params: params) { [self] task, responseObject, error in
  83. print("正在获取数据")
  84. if (error == nil && responseObject != nil) {
  85. let array = responseObject?["list"] ?? []
  86. if array != nil {
  87. //解析数据
  88. print("开始解析数据")
  89. weakSelf.parseData(data: array as! [NSDictionary], isNeedLocalComparison: true) { data in
  90. print("数据处理完毕")
  91. if data.count != 0 {
  92. info = data.first!
  93. completion(data.first, responseObject, nil)
  94. }
  95. }
  96. for model in array as! [NSDictionary] {
  97. let jsonString: String = (model["detail"] as? String) ?? ""
  98. let jsonData: Data = jsonString.data(using: .utf8)!
  99. let dict = try?JSONSerialization.jsonObject(with: jsonData)
  100. infoDict = dict as! NSDictionary
  101. }
  102. } else {
  103. print("解析数据失败array")
  104. completion(nil, responseObject, error)
  105. }
  106. } else {
  107. print("解析数据失败数据不存在")
  108. completion(nil, responseObject, error)
  109. }
  110. }
  111. }
  112. }
  113. extension KMAdvertisementManager {
  114. //MARK: data
  115. /**
  116. @abstract 解析数据
  117. @param data 传入参数 NSDictionary
  118. @param isNeedLocalComparison 是否需要对比本地版本,如果不一样将会刷新
  119. @return KMAdvertisementModel
  120. */
  121. public func parseData(data: [NSDictionary], isNeedLocalComparison: Bool ,completion:(_ result: [KMAdvertisementInfo]) -> Void) -> Void {
  122. //获取缓存数据
  123. var isNeedSave = false
  124. let cacheData = KMAdvertisementCache.default.readData()
  125. var resultArray:[KMAdvertisementInfo] = []
  126. for model in data {
  127. if (isNeedLocalComparison) {
  128. if (self.allowLoadData(data: model)) {
  129. let jsonString: String = (model["detail"] as? String) ?? ""
  130. let jsonData: Data = jsonString.data(using: .utf8)!
  131. let dict = try?JSONSerialization.jsonObject(with: jsonData)
  132. let decoder = JSONDecoder()
  133. // decoder.dataDecodingStrategy = .base64
  134. // decoder.keyDecodingStrategy = .convertFromSnakeCase //带下划线命名
  135. decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+∞", negativeInfinity: "-∞", nan: "NaN")
  136. #if DEBUG
  137. //MARK: 测试使用
  138. var advertisementModel = try! decoder.decode(KMAdvertisementInfo.self, from: jsonData)
  139. if (self.allowLoadContentData(data: advertisementModel)) {
  140. resultArray.append(self.allowLoadItemData(advertisementModel))
  141. isNeedSave = true
  142. }
  143. #else
  144. // MARK: 此处try 使用 ? ,如果数据出问题 advertisementModel将无参数, 测试时使用!
  145. var advertisementModel = try? decoder.decode(KMAdvertisementInfo.self, from: jsonData)
  146. if (advertisementModel != nil) {
  147. if (self.allowLoadContentData(data: advertisementModel!)) {
  148. resultArray.append(self.allowLoadItemData(advertisementModel!))
  149. isNeedSave = true
  150. }
  151. }
  152. #endif
  153. }
  154. }
  155. }
  156. if isNeedSave && isNeedLocalComparison {
  157. KMAdvertisementCache.default.saveData(data: data)
  158. print("已更新本地数据")
  159. } else {
  160. print("不需要更新本地数据")
  161. }
  162. completion(resultArray)
  163. }
  164. func allowLoadData(data: NSDictionary) -> Bool {
  165. var result = false
  166. let status = (data["status"] as? Int) ?? 0
  167. let app_name: String = data["app_name"] as? String ?? ""
  168. if (status == 1 &&
  169. app_name == configuration.appName.string()) {
  170. result = true
  171. }
  172. return result
  173. }
  174. func allowLoadContentData(data: KMAdvertisementInfo) -> Bool {
  175. var result = true
  176. return result
  177. }
  178. // func allowLoadContentData(data: KMAdvertisementModel) -> Bool {
  179. // var result = false
  180. //
  181. // let time: NSInteger = NSInteger(KMAdvertisementTimeStampConversion.getCurrentTimeInterval())!
  182. // let startTime: NSInteger = NSInteger(data.startTime!)!
  183. // let endTime: NSInteger = NSInteger(data.endTime!)!
  184. // let platform = configuration.platform
  185. // let subscribeType = configuration.subscribeType
  186. // let version = data.version ?? "1.0"
  187. // let localVersion = self.getLocalVersion()
  188. // let hidden = data.hidden ?? false
  189. //
  190. // if (time >= startTime &&
  191. // time <= endTime &&
  192. // platform == data.platform &&
  193. // self.compareVersion(nowVersion:localVersion, newVersion: version) &&
  194. // (subscribeType == data.subscribeType || data.subscribeType == .all) &&
  195. // !hidden) {
  196. // result = true
  197. // }
  198. // return result
  199. // }
  200. //过滤item是否显示
  201. func allowLoadItemData(_ data: KMAdvertisementInfo) -> KMAdvertisementInfo {
  202. let advertisement = data.advertisement
  203. advertisement?.content = self.canShow(data: (advertisement?.content)!)
  204. data.advertisement = advertisement
  205. let recommondContent = data.recommondContent
  206. let recommondContentOther = recommondContent?.recommondContentOther
  207. let recommondContentPDFPro = recommondContent?.recommondContentPDFPro
  208. recommondContentOther?.content = self.canShow(data: (recommondContentOther?.content)!)
  209. recommondContentPDFPro?.content = self.canShow(data: (recommondContentPDFPro?.content)!)
  210. recommondContent?.recommondContentOther = recommondContentOther
  211. recommondContent?.recommondContentPDFPro = recommondContentPDFPro
  212. data.recommondContent = recommondContent
  213. return data;
  214. }
  215. func canShow(data: [KMAdvertisementItemInfo]) -> [KMAdvertisementItemInfo] {
  216. var dataArray: [KMAdvertisementItemInfo] = []
  217. for item in data {
  218. let currentTime = Int(NSDate.init().timeIntervalSince1970 * 1000)
  219. if item.show == "1" &&
  220. currentTime > Int(item.startTime ?? "0") ?? currentTime &&
  221. currentTime < Int(item.endTime ?? "0") ?? currentTime {
  222. var canAdd = true
  223. if item.subscriptionType == "1" {
  224. if (IAPProductsManager.default().isAvailableAllFunction()) {
  225. canAdd = false
  226. }
  227. } else if item.subscriptionType == "2" {
  228. if (IAPProductsManager.default().isAvailableAllFunction() == false) {
  229. canAdd = false
  230. }
  231. }
  232. if canAdd {
  233. dataArray.append(item)
  234. }
  235. }
  236. }
  237. return dataArray
  238. }
  239. // + (BOOL)checkAdvertisementValid:(KMRecommondInfo *)info {
  240. // #if DEBUG
  241. // [[NSUserDefaults standardUserDefaults] removeObjectForKey:info.versionKey];
  242. // #endif
  243. // if ([[NSUserDefaults standardUserDefaults] objectForKey:info.versionKey]) {
  244. // return NO;
  245. // }
  246. // if (!info.show) {
  247. // return NO;
  248. // }
  249. // if (info.showType == KMRecommondShowType_Lite) {
  250. // if ([[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  251. // return NO;
  252. // }
  253. // } else if (info.showType == KMRecommondShowType_Pro) {
  254. // if (![[IAPProductsManager defaultManager] isAvailableAllFunction]) {
  255. // return NO;
  256. // }
  257. // }
  258. // return YES;
  259. // }
  260. // func allowLoadItemData(_ data: KMAdvertisementModel) -> KMAdvertisementModel {
  261. // //获取缓存数据
  262. // if (UserDefaults.standard.object(forKey: "KMAdvertisementShowScroll_iOS") == nil) {
  263. // UserDefaults.standard.set([], forKey: "KMAdvertisementShowScroll_iOS")
  264. // }
  265. // let cacheArray: [String] = UserDefaults.standard.object(forKey: "KMAdvertisementShowScroll_iOS") as! [String]
  266. //
  267. // let model = data
  268. // var sections: [KMAdvertisementModelSection] = []
  269. // for section in data.content! {
  270. // var items: [KMAdvertisementModelItem] = []
  271. // for item in section.content! {
  272. // let timeString = KMAdvertisementTimeStampConversion.getCurrentTimeInterval()
  273. // let time: NSInteger = NSInteger(timeString)!
  274. // let startTime: NSInteger = NSInteger(item.startTime ?? timeString)!
  275. // let endTime: NSInteger = NSInteger(item.endTime ?? timeString)!
  276. // let hidden = item.hidden ?? false
  277. //
  278. //// print(hidden ? "隐藏" : "显示")
  279. // if (!hidden &&
  280. // time >= startTime &&
  281. // time <= endTime &&
  282. // !cacheArray.contains(item.productID ?? "")) {
  283. // items.append(item)
  284. // }
  285. // }
  286. // section.content = items
  287. // sections.append(section)
  288. // }
  289. // model.content = sections
  290. // return model
  291. // }
  292. //获取本地版本号
  293. func getLocalVersion() -> String {
  294. var localVersion = ""
  295. if let v: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
  296. localVersion = v
  297. }
  298. return localVersion
  299. }
  300. func compareVersion(nowVersion: String, newVersion: String) -> Bool {
  301. let nowArray = nowVersion.split(separator: ".")
  302. let newArray = newVersion.split(separator: ".")
  303. let big = nowArray.count > newArray.count ? newArray.count : nowArray.count
  304. if big != 0 {
  305. for index in 0...big - 1 {
  306. let first = nowArray[index]
  307. let second = newArray[index]
  308. if Int(first)! < Int(second)! {
  309. return true
  310. }
  311. if index == big - 1 {
  312. if Int(first)! <= Int(second)! {
  313. return true
  314. }
  315. }
  316. }
  317. } else {
  318. return true
  319. }
  320. return false
  321. }
  322. }