KMFirebaseRemoteConfig.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import Foundation
  2. import FirebaseRemoteConfig
  3. enum KMRemoteConfigFetchStatus: Int {
  4. case success
  5. case failure
  6. }
  7. let KMFirebaseRemateConfigRequestIsSuccessful = "KMFirebaseRemateConfigRequestIsSuccessful"
  8. let KMFirebaseRemateConfigFinishNoti = "KMFirebaseRemateConfigFinishNoti"
  9. typealias KMRemoteConfigFetchCompletion = (_ status: KMRemoteConfigFetchStatus, _ error: Error?) -> Void
  10. @objcMembers class KMKdanRemoteConfig: NSObject {
  11. private let kIsDisplayAdsKey = "isDisplayAds"
  12. private let kIsDisplayAdsEvaluateAfterKey = "isDisplayAdsEvaluateAfter"
  13. private let kDisplayAdsUrlConfigKey = "displayAdsUrl"
  14. private let kDisplayHouseAdsUrlConfigKey = "displayHouseAdsUrl"
  15. private let kRefreshAdsRateDayKey = "refreshAdsRate"
  16. private let kRefreshAdsRateDayEvaluateAfterKey = "refreshAdsRateEvaluateAfter"
  17. private let kRefreshAdsDateDayKey = "refreshAdsDate"
  18. private let kRefreshAdsDateDayEvaluateAfterKey = "refreshAdsDateEvaluateAfter"
  19. private let kCloseIntervalDateDayKey = "closeIntervalDate"
  20. private let kCloseIntervalDateDayEvaluateAfterKey = "closeIntervalDateEvaluateAfter"
  21. private let kAppEvaluateBeforeAdsCountKey = "appEvaluateBeforeAdsCount"
  22. private let kAppEvaluateAfterAdsCountKey = "appEvaluateAfterAdsCount"
  23. static let remoteConfig = KMKdanRemoteConfig()
  24. private var remoteConfigDatas: [String: Any] = [:]
  25. private var userInfo: [String: Any] = [:]
  26. private lazy var firebaseConfig: RemoteConfig = {
  27. let config = RemoteConfig.remoteConfig()
  28. let settings = RemoteConfigSettings()
  29. settings.minimumFetchInterval = 0
  30. config.configSettings = settings
  31. #if VERSION_FREE
  32. config.setDefaults(fromPlist: "RemoteConfigDefaults")
  33. #else
  34. config.setDefaults(fromPlist: "ProRemoteConfigDefaults")
  35. #endif
  36. return config
  37. }()
  38. override init() {
  39. super.init()
  40. let mainBundleString = Bundle.main.bundleIdentifier ?? ""
  41. var dataPath: String?
  42. #if VERSION_DMG
  43. dataPath = Bundle.main.path(forResource: "DMGRemoteConfigDefaults", ofType: "plist")
  44. #else
  45. #if VERSION_FREE
  46. dataPath = Bundle.main.path(forResource: "RemoteConfigDefaults", ofType: "plist")
  47. #else
  48. dataPath = Bundle.main.path(forResource: "ProRemoteConfigDefaults", ofType: "plist")
  49. #endif
  50. #endif
  51. if let path = dataPath, let dict = NSDictionary(contentsOfFile: path) as? [String: Any] {
  52. self.userInfo = dict
  53. }
  54. }
  55. func fetch(completionHandler: @escaping KMRemoteConfigFetchCompletion) {
  56. let mainBundleString = Bundle.main.bundleIdentifier ?? ""
  57. let configuration = URLSessionConfiguration.default
  58. configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
  59. configuration.urlCache = URLCache.shared
  60. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  61. let params = "app_code=\(mainBundleString)&app_version=\(appVersion)&key=DisplayAds"
  62. var urlString = "http://store.pdfreaderpro.com:3018/api/get_config"
  63. #if DEBUG
  64. urlString = "http://test-store.kdan.cn:3018/api/get_config"
  65. #endif
  66. if let url = URL(string: "\(urlString)?\(params)") {
  67. var request = URLRequest(url: url)
  68. request.httpMethod = "GET"
  69. request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  70. let session = URLSession(configuration: configuration)
  71. let task = session.dataTask(with: request) { data, response, error in
  72. if let error = error {
  73. completionHandler(.failure, error)
  74. } else if let data = data {
  75. do {
  76. if let datas = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
  77. let displayAds = datas["data"] as? [String: Any] {
  78. #if VERSION_DMG
  79. if let dmg = displayAds["DisplayAds"] as? String {
  80. if let jsonData = dmg.data(using: .utf8),
  81. let dic = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any],
  82. let remoteConfigDatas = dic["dmg"] {
  83. self.remoteConfigDatas = remoteConfigDatas as! [String : Any]
  84. }
  85. }
  86. #else
  87. if let store = displayAds["DisplayAds"] as? String {
  88. if let jsonData = store.data(using: .utf8),
  89. let dic = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any],
  90. let remoteConfigDatas = dic["store"] {
  91. self.remoteConfigDatas = remoteConfigDatas as! [String : Any]
  92. }
  93. }
  94. #endif
  95. }
  96. completionHandler(.success, nil)
  97. } catch {
  98. completionHandler(.failure, error)
  99. }
  100. }
  101. NotificationCenter.default.post(name: Notification.Name(KMFirebaseRemateConfigRequestIsSuccessful), object: self, userInfo: nil)
  102. }
  103. task.resume()
  104. }
  105. }
  106. // FIRRemoteConfigFetchStatus status,
  107. // NSError *_Nullable error
  108. func fetchWithRemoteConfigCompletionHandler(completionHandler: @escaping ((_ status: RemoteConfigFetchStatus, _ error: Error?)->Void)) {
  109. let expirationDuration: TimeInterval = 0
  110. // If your app is using developer mode, expirationDuration is set to 0, so each fetch will
  111. // retrieve values from the Remote Config service.
  112. // TimeInterval is set to expirationDuration here, indicating the next fetch request will use
  113. // data fetched from the Remote Config service, rather than cached parameter values, if cached
  114. // parameter values are more than expirationDuration seconds old. See Best Practices in the
  115. // README for more information.
  116. self.firebaseConfig.fetch(withExpirationDuration: expirationDuration) { status, error in
  117. if status == .success {
  118. self.firebaseConfig.activate { changed, error in
  119. // Handle activation completion if needed
  120. }
  121. }
  122. NotificationCenter.default.post(name: Notification.Name(KMFirebaseRemateConfigFinishNoti), object: self, userInfo: nil)
  123. completionHandler(status, error)
  124. }
  125. }
  126. func isDisplayAds() -> Bool {
  127. var isDisplayAds = userInfo[kIsDisplayAdsKey] as? Bool ?? true
  128. if let value = remoteConfigDatas[kIsDisplayAdsKey] as? Bool {
  129. isDisplayAds = value
  130. }
  131. return isDisplayAds
  132. }
  133. func isDisplayAdsEvaluateAfter() -> Bool {
  134. var isDisplayAds = userInfo[kIsDisplayAdsEvaluateAfterKey] as? Bool ?? true
  135. if let value = remoteConfigDatas[kIsDisplayAdsEvaluateAfterKey] as? Bool {
  136. isDisplayAds = value
  137. }
  138. return isDisplayAds
  139. }
  140. func displayHouseAdsUrl() -> String {
  141. var adsUrl = userInfo[kDisplayHouseAdsUrlConfigKey] as? String ?? ""
  142. if let value = remoteConfigDatas[kDisplayHouseAdsUrlConfigKey] as? String {
  143. adsUrl = value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  144. }
  145. return adsUrl
  146. }
  147. func displayAdsUrl() -> String {
  148. var adsUrl = userInfo[kDisplayAdsUrlConfigKey] as? String ?? ""
  149. if let value = remoteConfigDatas[kDisplayAdsUrlConfigKey] as? String {
  150. adsUrl = value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  151. }
  152. return adsUrl
  153. }
  154. func refreshAdsRate() -> Int {
  155. var adsRate = userInfo[kRefreshAdsRateDayKey] as? Int ?? 0
  156. if let value = remoteConfigDatas[kRefreshAdsRateDayKey] as? String {
  157. adsRate = Int(value)!
  158. }
  159. return adsRate
  160. }
  161. func refreshAdsRateEvaluateAfter() -> Int {
  162. var adsRate = userInfo[kRefreshAdsRateDayEvaluateAfterKey] as? Int ?? 0
  163. if let value = remoteConfigDatas[kRefreshAdsRateDayEvaluateAfterKey] as? String {
  164. adsRate = Int(value)!
  165. }
  166. return adsRate
  167. }
  168. func refreshAdsDate() -> Int {
  169. var adsDate = userInfo[kRefreshAdsDateDayKey] as? Int ?? 180
  170. if let value = remoteConfigDatas[kRefreshAdsDateDayKey] as? String {
  171. adsDate = Int(value)!
  172. }
  173. return adsDate
  174. }
  175. func refreshAdsDateEvaluateAfter() -> Int {
  176. var adsDate = userInfo[kRefreshAdsDateDayEvaluateAfterKey] as? Int ?? 180
  177. if let value = remoteConfigDatas[kRefreshAdsDateDayEvaluateAfterKey] as? String {
  178. adsDate = Int(value)!
  179. }
  180. return adsDate
  181. }
  182. func closeIntervalDate() -> Int {
  183. var intervalDate = userInfo[kCloseIntervalDateDayKey] as? Int ?? 0
  184. if let value = remoteConfigDatas[kCloseIntervalDateDayKey] as? String {
  185. intervalDate = Int(value)!
  186. }
  187. return intervalDate
  188. }
  189. func closeIntervalDateEvaluateAfter() -> Int {
  190. var intervalDate = userInfo[kCloseIntervalDateDayEvaluateAfterKey] as? Int ?? 0
  191. if let value = remoteConfigDatas[kCloseIntervalDateDayEvaluateAfterKey] as? String {
  192. intervalDate = Int(value)!
  193. }
  194. return intervalDate
  195. }
  196. func appEvaluateBeforeAdsCount() -> Int {
  197. var evaluateCount = userInfo[kAppEvaluateBeforeAdsCountKey] as? Int ?? 1
  198. if let value = remoteConfigDatas[kAppEvaluateBeforeAdsCountKey] as? String {
  199. evaluateCount = Int(value)!
  200. }
  201. return evaluateCount
  202. }
  203. func appEvaluateAfterAdsCount() -> Int {
  204. var evaluateCount = userInfo[kAppEvaluateAfterAdsCountKey] as? Int ?? 1
  205. if let value = remoteConfigDatas[kAppEvaluateAfterAdsCountKey] as? String {
  206. evaluateCount = Int(value)!
  207. }
  208. return evaluateCount
  209. }
  210. func showSDKRecommendInfo() -> Bool {
  211. guard firebaseConfig.lastFetchStatus == .success else {
  212. return false
  213. }
  214. return firebaseConfig["SDKRecommendKey"].boolValue
  215. }
  216. func showAPP_AveragePrice() -> Bool {
  217. guard firebaseConfig.lastFetchStatus == .success else {
  218. return false
  219. }
  220. return firebaseConfig["ShowAPP_AveragePrice"].boolValue
  221. }
  222. func showHelp_More_RecommendLink() -> Bool {
  223. guard firebaseConfig.lastFetchStatus == .success else {
  224. return false
  225. }
  226. return firebaseConfig["Help_More_Link_Recommend"].boolValue
  227. }
  228. }