KMAdvertisementManager.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. //
  2. // KMAdvertisementManager.swift
  3. // KMAdvertisement
  4. //
  5. // Created by lizhe on 2022/11/23.
  6. // 广告管理
  7. #if os(OSX)
  8. import AppKit
  9. public typealias UIImage = NSImage
  10. public typealias UIView = NSView
  11. public typealias UIButton = NSButton
  12. public typealias UIScrollView = NSScrollView
  13. public typealias UIColor = NSColor
  14. public typealias UIFont = NSFont
  15. public typealias UITextView = NSTextView
  16. public typealias UIImageView = NSImageView
  17. public typealias UIEvent = NSEvent
  18. public typealias UIBezierPath = NSBezierPath
  19. public typealias UITextField = NSTextField
  20. public typealias UIEdgeInsets = NSEdgeInsets
  21. #elseif os(iOS)
  22. import UIKit
  23. public typealias NSImage = UIImage
  24. public typealias NSView = UIView
  25. public typealias NSButton = UIButton
  26. public typealias NSScrollView = UIScrollView
  27. public typealias NSColor = UIColor
  28. public typealias NSFont = UIFont
  29. public typealias NSTextView = UITextView
  30. public typealias NSImageView = UIImageView
  31. public typealias NSEvent = UIEvent
  32. public typealias NSBezierPath = UIBezierPath
  33. public typealias NSTextField = UILabel
  34. public typealias NSEdgeInsets = UIEdgeInsets
  35. #endif
  36. @objcMembers open class KMAdvertisementManager: NSObject {
  37. //单例
  38. @objc public static let manager = KMAdvertisementManager()
  39. @objc public var configuration: KMAdvertisementConfig = KMAdvertisementConfig()
  40. /**
  41. @abstract 测试模式,默认为false
  42. */
  43. @objc public var debug: Bool = false
  44. /**
  45. @abstract 初始化数据
  46. @param appID 产品名称
  47. @param subscribeType 订阅状态,可单独在configuration设置
  48. @param platform 平台
  49. @return
  50. */
  51. @objc public func initConfig(appName: KMAdvertisementAppNameType,
  52. subscribeType:KMAdvertisementSubscribeType,
  53. platform: KMAdvertisementPlatformType) {
  54. configuration.initParameters(appName: appName, subscribeType: subscribeType, platform: platform)
  55. }
  56. }
  57. extension KMAdvertisementManager {
  58. //MARK: request
  59. /**
  60. @abstract 获取数据
  61. @param data 传入参数 类型为KMAdvertisementModel
  62. @return
  63. */
  64. @objc public func fetchData(completion:@escaping (_ data: [KMAdvertisementModel]?, _ error:Error?) -> Void) -> Void {
  65. var version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString").debugDescription
  66. if (version.count == 0) {
  67. version = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion").debugDescription
  68. version = version.replacingOccurrences(of: ".", with: "")
  69. }
  70. let urlString = configuration.activityBaseURL() + "/api/advertise"
  71. let params: [String:Any] = ["app_name": configuration.appName.string(),
  72. "app_version": version]
  73. unowned let weakSelf = self
  74. KMAdvertisementRequestServer.requestServer.request(urlString: urlString, method: "GET", params: params) { task, responseObject, error in
  75. if (error == nil && responseObject != nil) {
  76. let array = responseObject?["list"] ?? []
  77. //保存数据
  78. KMAdvertisementCache.default.saveData(data: array as! [NSDictionary])
  79. //解析数据
  80. weakSelf.parseData(data: array as! [NSDictionary]) { data in
  81. completion(data, nil)
  82. }
  83. } else {
  84. //获取缓存数据
  85. let cacheData = KMAdvertisementCache.default.readData()
  86. if cacheData.count != 0 {
  87. weakSelf.parseData(data: cacheData) { data in
  88. completion(data, nil)
  89. }
  90. } else {
  91. completion(nil, error!)
  92. }
  93. }
  94. }
  95. }
  96. }
  97. extension KMAdvertisementManager {
  98. //MARK: show
  99. /**
  100. @abstract 显示视图
  101. @param type 显示类型 <KMAdvertisementShowType>
  102. @param data 显示数据 <KMAdvertisementModel>
  103. @param superView 父视图 <NSView>
  104. @return KMAdvertisementModel
  105. */
  106. @objc public func show(type: KMAdvertisementShowType, data: KMAdvertisementModel?, superView: NSView?, _ action: KMAdvertisementActionCompletion?) -> NSView {
  107. return self.show(type: type, data: data, superView: superView, action, nil)
  108. }
  109. @objc public func show(type: KMAdvertisementShowType, data: KMAdvertisementModel?, superView: NSView?, _ action: KMAdvertisementActionCompletion?, _ loadCompletion: KMAdvertisementLoadCompletion?) -> NSView {
  110. var view = KMAdvertisementBaseView()
  111. #if os(OSX)
  112. if data != nil {
  113. if type == .list {
  114. view = KMAdvertisementTableView.init(data: data!, superView: superView!)
  115. } else if type == .view {
  116. view = KMAdvertisementShowView.init(data: data!, superView: superView!)
  117. }
  118. }
  119. #else
  120. if data != nil {
  121. if type == .scroll {
  122. view = KMAdvertisementShowScroll_iOS.init(data: data!, superView: superView!)
  123. } else if type == .view {
  124. view = KMAdvertisementShowView_iOS.init(data: data!, superView: superView!)
  125. }
  126. }
  127. #endif
  128. if action == nil {
  129. view.actionCompletion = { tap, content in
  130. self.transitionAction(item: content)
  131. }
  132. } else {
  133. view.actionCompletion = action
  134. }
  135. if loadCompletion == nil {
  136. } else {
  137. view.loadCompletion = loadCompletion
  138. }
  139. return view
  140. }
  141. func transitionAction(item: KMAdvertisementModelItem) {
  142. if (item.actionType == .URL) {
  143. let string = item.linkURL?.en ?? ""
  144. #if os(iOS)
  145. if UIApplication.shared.canOpenURL(URL(string: string )!) {
  146. UIApplication.shared.open(URL(string: string )!, options: [:])
  147. }
  148. #elseif os(OSX)
  149. if NSWorkspace.shared.open(URL.init(string: string)!) {
  150. NSWorkspace.shared.open(URL.init(string: string)!)
  151. }
  152. #endif
  153. print("链接" + string)
  154. } else if (item.actionType == .comparative) {
  155. print("比较表")
  156. } else {
  157. print("其他")
  158. }
  159. }
  160. }
  161. extension KMAdvertisementManager {
  162. //MARK: data
  163. /**
  164. @abstract 解析数据
  165. @param data 传入参数 NSDictionary
  166. @return KMAdvertisementModel
  167. */
  168. public func parseData(data: [NSDictionary], completion:(_ result: [KMAdvertisementModel]) -> Void) -> Void {
  169. if (data.count != 0) {
  170. KMAdvertisementCache.default.saveData(data: data)
  171. }
  172. for model in data {
  173. var resultArray:[KMAdvertisementModel] = []
  174. if (self.allowLoadData(data: model)) {
  175. let jsonString: String = (model["detail"] as? String) ?? ""
  176. let jsonData: Data = jsonString.data(using: .utf8)!
  177. let decoder = JSONDecoder()
  178. // decoder.dataDecodingStrategy = .base64
  179. // decoder.keyDecodingStrategy = .convertFromSnakeCase //带下划线命名
  180. decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+∞", negativeInfinity: "-∞", nan: "NaN")
  181. #if DEBUG
  182. //MARK: 测试使用
  183. var advertisementModel = try! decoder.decode(KMAdvertisementModel.self, from: jsonData)
  184. if (self.allowLoadContentData(data: advertisementModel)) {
  185. resultArray.append(self.allowLoadItemData(advertisementModel))
  186. }
  187. #else
  188. // MARK: 此处try 使用 ? ,如果数据出问题 advertisementModel将无参数, 测试时使用!
  189. var advertisementModel = try? decoder.decode(KMAdvertisementModel.self, from: jsonData)
  190. if (advertisementModel != nil) {
  191. if (self.allowLoadContentData(data: advertisementModel!)) {
  192. resultArray.append(self.allowLoadItemData(advertisementModel!))
  193. }
  194. }
  195. #endif
  196. }
  197. completion(resultArray)
  198. }
  199. }
  200. func allowLoadData(data: NSDictionary) -> Bool {
  201. var result = false
  202. let status = (data["status"] as? Int) ?? 0
  203. let app_name: String = data["app_name"] as? String ?? ""
  204. if (status == 1 &&
  205. app_name == configuration.appName.string()) {
  206. result = true
  207. }
  208. return result
  209. }
  210. func allowLoadContentData(data: KMAdvertisementModel) -> Bool {
  211. var result = false
  212. let time: NSInteger = NSInteger(KMAdvertisementTimeStampConversion.getCurrentTimeInterval())!
  213. let startTime: NSInteger = NSInteger(data.startTime!)!
  214. let endTime: NSInteger = NSInteger(data.endTime!)!
  215. let platform = configuration.platform
  216. let subscribeType = configuration.subscribeType
  217. let version = data.version ?? "1.0"
  218. let localVersion = self.getLocalVersion()
  219. let hidden = data.hidden ?? false
  220. if (time >= startTime &&
  221. time <= endTime &&
  222. platform == data.platform &&
  223. self.compareVersion(nowVersion:localVersion, newVersion: version) &&
  224. (subscribeType == data.subscribeType || data.subscribeType == .all) &&
  225. !hidden) {
  226. result = true
  227. }
  228. return result
  229. }
  230. //过滤item是否显示
  231. func allowLoadItemData(_ data: KMAdvertisementModel) -> KMAdvertisementModel {
  232. //获取缓存数据
  233. if (UserDefaults.standard.object(forKey: "KMAdvertisementShowScroll_iOS") == nil) {
  234. UserDefaults.standard.set([], forKey: "KMAdvertisementShowScroll_iOS")
  235. }
  236. let cacheArray: [String] = UserDefaults.standard.object(forKey: "KMAdvertisementShowScroll_iOS") as! [String]
  237. let model = data
  238. var sections: [KMAdvertisementModelSection] = []
  239. for section in data.content! {
  240. var items: [KMAdvertisementModelItem] = []
  241. for item in section.content! {
  242. let timeString = KMAdvertisementTimeStampConversion.getCurrentTimeInterval()
  243. let time: NSInteger = NSInteger(timeString)!
  244. let startTime: NSInteger = NSInteger(item.startTime ?? timeString)!
  245. let endTime: NSInteger = NSInteger(item.endTime ?? timeString)!
  246. let hidden = item.hidden ?? false
  247. print(hidden ? "隐藏" : "显示")
  248. if (!hidden &&
  249. time >= startTime &&
  250. time <= endTime &&
  251. !cacheArray.contains(item.productID ?? "")) {
  252. items.append(item)
  253. }
  254. }
  255. section.content = items
  256. sections.append(section)
  257. }
  258. model.content = sections
  259. return model
  260. }
  261. //获取本地版本号
  262. func getLocalVersion() -> String {
  263. var localVersion = ""
  264. if let v: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
  265. localVersion = v
  266. }
  267. return localVersion
  268. }
  269. func compareVersion(nowVersion: String, newVersion: String) -> Bool {
  270. let nowArray = nowVersion.split(separator: ".")
  271. let newArray = newVersion.split(separator: ".")
  272. let big = nowArray.count > newArray.count ? newArray.count : nowArray.count
  273. for index in 0...big - 1 {
  274. let first = nowArray[index]
  275. let second = newArray[index]
  276. if Int(first)! <= Int(second)! {
  277. return true
  278. }
  279. }
  280. return false
  281. }
  282. }
  283. extension KMAdvertisementManager {
  284. // //MARK: image
  285. // public func dynamic_sdkBundle_image()-> NSImage? {
  286. // // class: 库里 任意class, dynamic bundle 和 mainBundle 不是同一个
  287. // let bundle = Bundle(for: KMAdvertisementManager.self)
  288. //// let mainBundle = Bundle.main
  289. // let path = bundle.path(forResource: "KMAdvertisement", ofType: "bundle")
  290. // if let path = path {
  291. // let sdkBundle = Bundle(path: path)
  292. // let filePath = sdkBundle?.pathForImageResource("1")
  293. // let image = NSImage.init(contentsOfFile: filePath!)
  294. //// let image = NSImage(named: "1", in: sdkBundle, compatibleWith: nil)
  295. // return image
  296. // }
  297. // return nil
  298. // }
  299. //
  300. // public func staticSdk_image() -> NSImage? {
  301. // // class: 库里 任意class
  302. // let bundle = Bundle(for: KMAdvertisementManager.self)
  303. // let path = bundle.path(forResource: "KMAdvertisement", ofType: "framework")
  304. // if let path = path {
  305. // let sdkBundle = Bundle(path: path)
  306. // let filePath = sdkBundle?.pathForImageResource("1")
  307. // let image = NSImage.init(contentsOfFile: filePath!)
  308. // return image
  309. // }
  310. // return nil
  311. // }
  312. }