KMAdvertisementManager.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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: true) { 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. for model in array as! [NSDictionary] {
  90. let jsonString: String = (model["detail"] as? String) ?? ""
  91. let jsonData: Data = jsonString.data(using: .utf8)!
  92. let dict = try?JSONSerialization.jsonObject(with: jsonData)
  93. infoDict = dict as! NSDictionary
  94. }
  95. weakSelf.parseData(data: array as! [NSDictionary], isNeedLocalComparison: true) { data in
  96. print("数据处理完毕")
  97. if data.count != 0 {
  98. info = data.first!
  99. completion(data.first, responseObject, nil)
  100. }
  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. // MARK: 此处try 使用 ? ,如果数据出问题 advertisementModel将无参数, 测试时使用!
  137. var advertisementModel = try? decoder.decode(KMAdvertisementInfo.self, from: jsonData)
  138. if (advertisementModel != nil) {
  139. if (self.allowLoadContentData(data: advertisementModel!)) {
  140. resultArray.append(self.allowLoadItemData(advertisementModel!))
  141. isNeedSave = true
  142. }
  143. }
  144. }
  145. }
  146. }
  147. if isNeedSave && isNeedLocalComparison {
  148. KMAdvertisementCache.default.saveData(data: data)
  149. print("已更新本地数据")
  150. } else {
  151. print("不需要更新本地数据")
  152. }
  153. completion(resultArray)
  154. }
  155. func allowLoadData(data: NSDictionary) -> Bool {
  156. var result = false
  157. let status = (data["status"] as? Int) ?? 0
  158. let app_name: String = data["app_name"] as? String ?? ""
  159. if (status == 1 &&
  160. app_name == configuration.appName.string()) {
  161. result = true
  162. }
  163. return result
  164. }
  165. func allowLoadContentData(data: KMAdvertisementInfo) -> Bool {
  166. var result = true
  167. return result
  168. }
  169. //过滤item是否显示
  170. func allowLoadItemData(_ data: KMAdvertisementInfo) -> KMAdvertisementInfo {
  171. let advertisement = data.advertisement
  172. advertisement?.content = self.canShow(data: (advertisement?.content)!)
  173. data.advertisement = advertisement
  174. let recommondContent = data.recommondContent
  175. let recommondContentOther = recommondContent?.recommondContentOther
  176. let recommondContentPDFPro = recommondContent?.recommondContentPDFPro
  177. recommondContentOther?.content = self.canShow(data: (recommondContentOther?.content)!)
  178. recommondContentPDFPro?.content = self.canShow(data: (recommondContentPDFPro?.content)!)
  179. recommondContent?.recommondContentOther = recommondContentOther
  180. recommondContent?.recommondContentPDFPro = recommondContentPDFPro
  181. data.recommondContent = recommondContent
  182. return data;
  183. }
  184. func canShow(data: [KMAdvertisementItemInfo]) -> [KMAdvertisementItemInfo] {
  185. var dataArray: [KMAdvertisementItemInfo] = []
  186. for item in data {
  187. let currentTime = Int(NSDate.init().timeIntervalSince1970 * 1000)
  188. if item.show == "1" &&
  189. currentTime > Int(item.startTime ?? "0") ?? currentTime &&
  190. currentTime < Int(item.endTime ?? "0") ?? currentTime {
  191. var canAdd = true
  192. if item.subscriptionType == "1" {
  193. if (IAPProductsManager.default().isAvailableAllFunction()) {
  194. canAdd = false
  195. }
  196. } else if item.subscriptionType == "2" {
  197. if (IAPProductsManager.default().isAvailableAllFunction() == false) {
  198. canAdd = false
  199. }
  200. }
  201. if canAdd {
  202. dataArray.append(item)
  203. }
  204. }
  205. }
  206. return dataArray
  207. }
  208. //获取本地版本号
  209. func getLocalVersion() -> String {
  210. var localVersion = ""
  211. if let v: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
  212. localVersion = v
  213. }
  214. return localVersion
  215. }
  216. func compareVersion(nowVersion: String, newVersion: String) -> Bool {
  217. let nowArray = nowVersion.split(separator: ".")
  218. let newArray = newVersion.split(separator: ".")
  219. let big = nowArray.count > newArray.count ? newArray.count : nowArray.count
  220. if big != 0 {
  221. for index in 0...big - 1 {
  222. let first = nowArray[index]
  223. let second = newArray[index]
  224. if Int(first)! < Int(second)! {
  225. return true
  226. }
  227. if index == big - 1 {
  228. if Int(first)! <= Int(second)! {
  229. return true
  230. }
  231. }
  232. }
  233. } else {
  234. return true
  235. }
  236. return false
  237. }
  238. }
  239. extension KMAdvertisementManager {
  240. static func checkAdvertisementValid(_ info: KMAdvertisementItemInfo) -> Bool {
  241. #if DEBUG
  242. UserDefaults.standard.removeObject(forKey: info.version ?? "")
  243. #endif
  244. if UserDefaults.standard.object(forKey: info.version ?? "") != nil {
  245. return false
  246. }
  247. if (info.show == nil) {
  248. return false
  249. }
  250. let currentTime = Int(NSDate.init().timeIntervalSince1970 * 1000)
  251. if currentTime > Int(info.startTime ?? "0") ?? currentTime &&
  252. currentTime < Int(info.endTime ?? "0") ?? currentTime {
  253. } else {
  254. return false
  255. }
  256. if info.subscriptionType == "1" {
  257. // if IAPProductsManager.default().isAvailableAllFunction() {
  258. if IAPProductsManager.default().isAvailableAllFunction() == true {
  259. return false
  260. }
  261. } else if info.subscriptionType == "2" {
  262. if !IAPProductsManager.default().isAvailableAllFunction() {
  263. return true
  264. }
  265. }
  266. return true
  267. }
  268. }