123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295 |
- //
- // KMAdvertisementManager.swift
- // KMAdvertisement
- //
- // Created by lizhe on 2022/11/23.
- // 广告管理
- #if os(OSX)
- import AppKit
- public typealias UIImage = NSImage
- public typealias UIView = NSView
- public typealias UIButton = NSButton
- public typealias UIScrollView = NSScrollView
- public typealias UIColor = NSColor
- public typealias UIFont = NSFont
- public typealias UITextView = NSTextView
- public typealias UIImageView = NSImageView
- public typealias UIEvent = NSEvent
- public typealias UIBezierPath = NSBezierPath
- public typealias UITextField = NSTextField
- public typealias UIEdgeInsets = NSEdgeInsets
- #elseif os(iOS)
- import UIKit
- public typealias NSImage = UIImage
- public typealias NSView = UIView
- public typealias NSButton = UIButton
- public typealias NSScrollView = UIScrollView
- public typealias NSColor = UIColor
- public typealias NSFont = UIFont
- public typealias NSTextView = UITextView
- public typealias NSImageView = UIImageView
- public typealias NSEvent = UIEvent
- public typealias NSBezierPath = UIBezierPath
- public typealias NSTextField = UILabel
- public typealias NSEdgeInsets = UIEdgeInsets
- #endif
- open class KMAdvertisementManager {
- //单例
- public static let manager = KMAdvertisementManager()
- public var configuration: KMAdvertisementConfig = KMAdvertisementConfig()
-
- /**
- @abstract 测试模式,默认为false
- */
- public var debug: Bool = false
-
- /**
- @abstract 初始化数据
- @param appID 产品名称
- @param subscribeType 订阅状态,可单独在configuration设置
- @param platform 平台
- @return
- */
- public func initConfig(appName: KMAdvertisementAppNameType,
- subscribeType:KMAdvertisementSubscribeType,
- platform: KMAdvertisementPlatformType) {
- configuration.initParameters(appName: appName, subscribeType: subscribeType, platform: platform)
- }
- }
- extension KMAdvertisementManager {
- //MARK: request
- /**
- @abstract 获取数据
- @param data 传入参数 类型为KMAdvertisementModel
- @return
- */
- public func fetchData(completion:@escaping (_ data: [KMAdvertisementModel]?, _ error:Error?) -> Void) -> Void {
- var version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString").debugDescription
- if (version.count == 0) {
- version = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion").debugDescription
- version = version.replacingOccurrences(of: ".", with: "")
- }
-
- let urlString = configuration.activityBaseURL() + "/api/advertise"
- let params: [String:Any] = ["app_name": configuration.appName.rawValue,
- "app_version": version]
-
- unowned let weakSelf = self
- KMAdvertisementRequestServer.requestServer.request(urlString: urlString, method: "GET", params: params) { task, responseObject, error in
- if (error == nil && responseObject != nil) {
- let array = responseObject?["list"] ?? []
- //保存数据
- KMAdvertisementCache.default.saveData(data: array as! [NSDictionary])
- //解析数据
- weakSelf.parseData(data: array as! [NSDictionary]) { data in
- completion(data, nil)
- }
- } else {
- //获取缓存数据
- let cacheData = KMAdvertisementCache.default.readData()
- if cacheData.count != 0 {
- weakSelf.parseData(data: cacheData) { data in
- completion(data, nil)
- }
- } else {
- completion(nil, error!)
- }
- }
- }
- }
- }
- extension KMAdvertisementManager {
- //MARK: show
- /**
- @abstract 显示视图
- @param type 显示类型 <KMAdvertisementShowType>
- @param data 显示数据 <KMAdvertisementModel>
- @param superView 父视图 <NSView>
- @return KMAdvertisementModel
- */
- public func show(type: KMAdvertisementShowType?, data: KMAdvertisementModel?, superView: NSView?, _ action: KMAdvertisementActionCompletion?) -> NSView {
- var view = KMAdvertisementBaseView()
- #if os(OSX)
- if data != nil {
- if type == .list {
- view = KMAdvertisementTableView.init(data: data!, superView: superView!)
- } else if type == .view {
- view = KMAdvertisementShowView.init(data: data!, superView: superView!)
- }
- }
- #else
- if data != nil {
- if type == .scroll {
- view = KMAdvertisementShowScroll_iOS.init(data: data!, superView: superView!)
- } else if type == .view {
- view = KMAdvertisementShowView_iOS.init(data: data!, superView: superView!)
- }
- }
- #endif
- if action == nil {
- view.actionCompletion = { content in
- self.transitionAction(item: content)
- }
- } else {
- view.actionCompletion = action
- }
- return view
- }
-
- func transitionAction(item: KMAdvertisementModel.Section.Content) {
- if (item.actionType == .URL) {
- let string = item.linkURL?.en ?? ""
- #if os(iOS)
- if UIApplication.shared.canOpenURL(URL(string: string )!) {
- UIApplication.shared.open(URL(string: string )!, options: [:])
- }
- #elseif os(OSX)
- if NSWorkspace.shared.open(URL.init(string: string)!) {
- NSWorkspace.shared.open(URL.init(string: string)!)
- }
- #endif
- print("链接" + string)
- } else if (item.actionType == .comparative) {
- print("比较表")
- }
- }
- }
- extension KMAdvertisementManager {
- //MARK: data
- /**
- @abstract 解析数据
- @param data 传入参数 NSDictionary
- @return KMAdvertisementModel
- */
- public func parseData(data: [NSDictionary], completion:(_ result: [KMAdvertisementModel]) -> Void) -> Void {
- if (data.count != 0) {
- KMAdvertisementCache.default.saveData(data: data)
- }
-
- for model in data {
- var resultArray:[KMAdvertisementModel] = []
- if (self.allowLoadData(data: model)) {
- let jsonString: String = (model["detail"] as? String) ?? ""
- let jsonData: Data = jsonString.data(using: .utf8)!
-
- let decoder = JSONDecoder()
- // decoder.dataDecodingStrategy = .base64
- // decoder.keyDecodingStrategy = .convertFromSnakeCase //带下划线命名
- decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+∞", negativeInfinity: "-∞", nan: "NaN")
- #if DEBUG
- //MARK: 测试使用
- let advertisementModel = try! decoder.decode(KMAdvertisementModel.self, from: jsonData)
- if (self.allowLoadContentData(data: advertisementModel)) {
- resultArray.append(advertisementModel)
- }
- #else
- // MARK: 此处try 使用 ? ,如果数据出问题 advertisementModel将无参数, 测试时使用!
- let advertisementModel = try? decoder.decode(KMAdvertisementModel.self, from: jsonData)
- if (advertisementModel != nil) {
- if (self.allowLoadContentData(data: advertisementModel)) {
- resultArray.append(advertisementModel!)
- }
- }
- #endif
- }
- completion(resultArray)
- }
- }
-
- func allowLoadData(data: NSDictionary) -> Bool {
- var result = false
-
- let status = (data["status"] as? Int) ?? 0
- let app_name: String = data["app_name"] as? String ?? ""
-
- if (status == 1 &&
- app_name == configuration.appName.rawValue) {
- result = true
- }
- return result
-
- }
-
- func allowLoadContentData(data: KMAdvertisementModel) -> Bool {
- var result = false
-
- let time: NSInteger = NSInteger(KMAdvertisementTimeStampConversion.getCurrentTimeInterval())!
- let startTime: NSInteger = NSInteger(data.startTime!)!
- let endTime: NSInteger = NSInteger(data.endTime!)!
- let platform = configuration.platform
- let subscribeType = configuration.subscribeType
- let version = data.version ?? "1.0"
- let localVersion = self.getLocalVersion()
-
- if (time >= startTime &&
- time <= endTime &&
- platform == data.platform &&
- self.compareVersion(nowVersion:localVersion, newVersion: version) &&
- subscribeType == data.subscribeType) {
- result = true
- }
- return result
- }
-
- //获取本地版本号
- func getLocalVersion() -> String {
- var localVersion = ""
- if let v: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
- localVersion = v
- }
- return localVersion
- }
-
- func compareVersion(nowVersion: String, newVersion: String) -> Bool {
- let nowArray = nowVersion.split(separator: ".")
- let newArray = newVersion.split(separator: ".")
- let big = nowArray.count > newArray.count ? newArray.count : nowArray.count
- for index in 0...big - 1 {
- let first = nowArray[index]
- let second = newArray[index]
- if Int(first)! <= Int(second)! {
- return true
- }
- }
- return false
- }
- }
- extension KMAdvertisementManager {
- // //MARK: image
- // public func dynamic_sdkBundle_image()-> NSImage? {
- // // class: 库里 任意class, dynamic bundle 和 mainBundle 不是同一个
- // let bundle = Bundle(for: KMAdvertisementManager.self)
- //// let mainBundle = Bundle.main
- // let path = bundle.path(forResource: "KMAdvertisement", ofType: "bundle")
- // if let path = path {
- // let sdkBundle = Bundle(path: path)
- // let filePath = sdkBundle?.pathForImageResource("1")
- // let image = NSImage.init(contentsOfFile: filePath!)
- //// let image = NSImage(named: "1", in: sdkBundle, compatibleWith: nil)
- // return image
- // }
- // return nil
- // }
- //
- // public func staticSdk_image() -> NSImage? {
- // // class: 库里 任意class
- // let bundle = Bundle(for: KMAdvertisementManager.self)
- // let path = bundle.path(forResource: "KMAdvertisement", ofType: "framework")
- // if let path = path {
- // let sdkBundle = Bundle(path: path)
- // let filePath = sdkBundle?.pathForImageResource("1")
- // let image = NSImage.init(contentsOfFile: filePath!)
- // return image
- // }
- // return nil
- // }
- }
|