KMRequestServer.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. //
  2. // KMRequestServer.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2023/2/22.
  6. //
  7. import Cocoa
  8. import AFNetworking
  9. @objc public enum KMRequestServerMethodType: Int {
  10. case post = 0
  11. case get
  12. case put
  13. case delete
  14. }
  15. public class KMRequestResultModel: NSObject {
  16. public var code: Int = 0
  17. public var msg: String?
  18. public var data: Any?
  19. public var result: Bool = false
  20. convenience init(dict: [String : Any]) {
  21. self.init()
  22. self.code = dict["code"] as? Int ?? 0
  23. self.msg = dict["msg"] as? String
  24. self.data = dict["data"]
  25. self.result = dict["result"] as? Bool ?? false
  26. }
  27. public func isSuccess() -> Bool {
  28. return self.code == 200
  29. }
  30. }
  31. typealias KMHttpRequestServerComplete = (_ task: URLSessionDataTask?, _ responseObject: AnyObject?, _ error: NSError?) -> Void
  32. @objcMembers class KMRequestServer: NSObject {
  33. @objc var sessionManager: AFHTTPSessionManager!
  34. @objc static let requestServer = KMRequestServer()
  35. @objc var task: URLSessionTask?
  36. override init() {
  37. super.init()
  38. let configuration: URLSessionConfiguration = URLSessionConfiguration.default
  39. sessionManager = AFHTTPSessionManager.init(sessionConfiguration: configuration)
  40. sessionManager.securityPolicy = AFSecurityPolicy.default()
  41. }
  42. public func request(urlString: String,
  43. method: KMRequestServerMethodType,
  44. params: Dictionary<String, Any>?,
  45. completion: KMHttpRequestServerComplete?) -> Void
  46. {
  47. self.request(urlString: urlString,
  48. method: method,
  49. params: params,
  50. requestSerializer: nil,
  51. completion: completion)
  52. }
  53. func request(urlString: String,
  54. method: KMRequestServerMethodType,
  55. params: Dictionary<String, Any>?,
  56. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  57. completion: KMHttpRequestServerComplete?) -> Void {
  58. self.request(urlString: urlString,
  59. method: method,
  60. params: params,
  61. requestSerializer: requestSerializer,
  62. body: nil,
  63. completion: completion)
  64. }
  65. func request(urlString: String,
  66. method: KMRequestServerMethodType,
  67. params: Dictionary<String, Any>?,
  68. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  69. body: ((_ formData:AFMultipartFormData) -> Void)?,
  70. completion: KMHttpRequestServerComplete?) -> Void {
  71. //每次请求需要重新创建
  72. sessionManager.requestSerializer = AFJSONRequestSerializer()
  73. sessionManager.responseSerializer = AFJSONResponseSerializer()
  74. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  75. sessionManager.requestSerializer.timeoutInterval = 60
  76. // [requestSerializer setValue:@"application/vnd.api+json;version=1" forHTTPHeaderField:@"Accept"];
  77. if (requestSerializer != nil) {
  78. requestSerializer!(sessionManager.requestSerializer);
  79. }
  80. if (method == .post) {
  81. if (body != nil) {
  82. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  83. body!(formData)
  84. } progress: { progress in
  85. } success: { task, responseObject in
  86. let responseObject = responseObject as AnyObject
  87. if (completion != nil) {
  88. completion!(task,responseObject,nil);
  89. }
  90. } failure: { task, error in
  91. if (completion != nil) {
  92. completion!(task, nil, error as NSError);
  93. }
  94. }
  95. } else {
  96. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  97. } success: { task, responseObject in
  98. if (completion != nil) {
  99. let responseObject = responseObject as AnyObject
  100. completion!(task,responseObject,nil);
  101. }
  102. } failure: { task, error in
  103. if (completion != nil) {
  104. completion!(task, nil, error as NSError);
  105. }
  106. }
  107. }
  108. } else if (method == .get) {
  109. self.task = sessionManager.get(urlString, parameters: params, headers: nil) { progress in
  110. } success: { task, responseObject in
  111. if (completion != nil) {
  112. let responseObject = responseObject as AnyObject
  113. completion!(task,responseObject,nil);
  114. }
  115. } failure: { task, error in
  116. if (completion != nil) {
  117. completion!(task, nil, error as NSError);
  118. }
  119. }
  120. }
  121. }
  122. /**
  123. 下载
  124. */
  125. func downLoad(urlString: String,
  126. filePath: String,
  127. progress: @escaping(_ progress: Progress) -> Void,
  128. completion: KMRequestServerComplete) {
  129. // /* 下载地址 */
  130. // NSURL *url = [NSURL URLWithString:urlString];
  131. // NSURLRequest *request = [NSURLRequest requestWithURL:url];
  132. // /* 开始请求下载 */
  133. // NSProgress *tProgress;
  134. // NSURLSessionDownloadTask *downloadTask = [_sessionManager downloadTaskWithRequest:request progress:&tProgress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
  135. // dispatch_async(dispatch_get_main_queue(), ^{
  136. // //如果需要进行UI操作,需要获取主线程进行操作
  137. // });
  138. // /* 设定下载到的位置 */
  139. // return [NSURL fileURLWithPath:filePath];
  140. //
  141. // } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
  142. // if (completion) {
  143. // completion(response,filePath,error);
  144. // }
  145. // }];
  146. //
  147. // if (progress) {
  148. // progress(tProgress);
  149. // }
  150. //
  151. // [downloadTask resume];
  152. }
  153. /**
  154. 翻译上传文件
  155. */
  156. func aiTranslation(urlString: String,
  157. params: Dictionary<String, Any>?,
  158. body: ((_ formData:AFMultipartFormData) -> Void)?,
  159. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  160. completion: KMHttpRequestServerComplete?) -> Void {
  161. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  162. sessionManager.requestSerializer.timeoutInterval = 60
  163. sessionManager.responseSerializer = AFJSONResponseSerializer()
  164. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  165. if (requestSerializer != nil) {
  166. requestSerializer!(sessionManager.requestSerializer);
  167. }
  168. if (body != nil) {
  169. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  170. body!(formData)
  171. } progress: { progress in
  172. } success: { task, responseObject in
  173. let responseObject = responseObject as AnyObject
  174. if (completion != nil) {
  175. completion!(task,responseObject,nil);
  176. }
  177. } failure: { task, error in
  178. if (completion != nil) {
  179. completion!(task, nil, error as NSError);
  180. }
  181. }
  182. } else {
  183. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  184. } success: { task, responseObject in
  185. if (completion != nil) {
  186. let responseObject = responseObject as AnyObject
  187. completion!(task,responseObject,nil);
  188. }
  189. } failure: { task, error in
  190. if (completion != nil) {
  191. completion!(task, nil, error as NSError);
  192. }
  193. }
  194. }
  195. }
  196. /**
  197. 文件翻译
  198. */
  199. func aiFileTranslateHandle(urlString: String,
  200. params: Dictionary<String, Any>?,
  201. body: ((_ formData:AFMultipartFormData) -> Void)?,
  202. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  203. completion: KMHttpRequestServerComplete?) -> Void {
  204. sessionManager.requestSerializer = AFJSONRequestSerializer()
  205. sessionManager.responseSerializer = AFJSONResponseSerializer()
  206. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  207. if (requestSerializer != nil) {
  208. requestSerializer!(sessionManager.requestSerializer);
  209. }
  210. if (body != nil) {
  211. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  212. body!(formData)
  213. } progress: { progress in
  214. } success: { task, responseObject in
  215. let responseObject = responseObject as AnyObject
  216. if (completion != nil) {
  217. completion!(task,responseObject,nil);
  218. }
  219. } failure: { task, error in
  220. if (completion != nil) {
  221. completion!(task, nil, error as NSError);
  222. }
  223. }
  224. } else {
  225. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  226. } success: { task, responseObject in
  227. if (completion != nil) {
  228. let responseObject = responseObject as AnyObject
  229. completion!(task,responseObject,nil);
  230. }
  231. } failure: { task, error in
  232. if (completion != nil) {
  233. completion!(task, nil, error as NSError);
  234. }
  235. }
  236. }
  237. }
  238. /**
  239. 重写
  240. */
  241. func aiRewriting(urlString: String,
  242. params: Dictionary<String, Any>?,
  243. body: ((_ formData:AFMultipartFormData) -> Void)?,
  244. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  245. completion: KMHttpRequestServerComplete?) -> Void {
  246. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  247. sessionManager.requestSerializer.timeoutInterval = 60
  248. sessionManager.responseSerializer = AFJSONResponseSerializer()
  249. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  250. if (requestSerializer != nil) {
  251. requestSerializer!(sessionManager.requestSerializer);
  252. }
  253. if (body != nil) {
  254. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  255. body!(formData)
  256. } progress: { progress in
  257. } success: { task, responseObject in
  258. let responseObject = responseObject as AnyObject
  259. if (completion != nil) {
  260. completion!(task,responseObject,nil);
  261. }
  262. } failure: { task, error in
  263. if (completion != nil) {
  264. completion!(task, nil, error as NSError);
  265. }
  266. }
  267. } else {
  268. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  269. } success: { task, responseObject in
  270. if (completion != nil) {
  271. let responseObject = responseObject as AnyObject
  272. completion!(task,responseObject,nil);
  273. }
  274. } failure: { task, error in
  275. if (completion != nil) {
  276. completion!(task, nil, error as NSError);
  277. }
  278. }
  279. }
  280. }
  281. /*
  282. status
  283. AFNetworkReachabilityStatusUnknown = -1, 不知道监测的是什么
  284. AFNetworkReachabilityStatusNotReachable = 0, 没有检测到网络
  285. AFNetworkReachabilityStatusReachableViaWWAN = 1, 蜂窝网
  286. AFNetworkReachabilityStatusReachableViaWiFi = 2, WIFI
  287. */
  288. func reachabilityStatusChange(block: @escaping(AFNetworkReachabilityStatus) ->Void) {
  289. // 1.创建网络监测单例
  290. let manager = AFNetworkReachabilityManager.shared()
  291. manager.setReachabilityStatusChange({ status in
  292. // 2.实现网络监测的回调
  293. block(status)
  294. })
  295. // 3.开始监测
  296. manager.startMonitoring()
  297. }
  298. }
  299. // MARK: - POST & GET
  300. let kURLAPI_memberSystemSSO_user_cancelReason = "/member-system-sso/user/cancelReason"
  301. let kURLAPI_memberSystemWebsite_activity_signIn = "/member-system-website/activity/signIn"
  302. // 判断用户是否处于试用后退订
  303. let kURLAPI_memberSystemSSO_user_judgeTrailCancel = "/member-system-sso/user/judgeTrailCancel"
  304. extension KMRequestServer {
  305. public class func Member_POST(url: String, params: [String : Any]?, callback: @escaping ((_ success: Bool, _ resultModel: KMRequestResultModel?, _ error: NSError?)->Void)) {
  306. // 获取 Token
  307. let token = KMMemberInfo.shared.access_token
  308. if token == "" {
  309. callback(false, nil, nil)
  310. return
  311. }
  312. // 拼接 URL
  313. let urlString = KMMemberCenterConfig().activityBaseURL() + url
  314. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  315. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  316. } completion: { task, responseObject, error in
  317. guard let dict = responseObject as? [String : Any] else {
  318. callback(false, nil, error)
  319. return
  320. }
  321. let model = KMRequestResultModel(dict: dict)
  322. callback(model.isSuccess(), model, error)
  323. }
  324. }
  325. public class func Member_GET(url: String, params: [String : Any]?, callback: @escaping ((_ success: Bool, _ resultModel: KMRequestResultModel?, _ error: NSError?)->Void)) {
  326. // 获取 Token
  327. let token = KMMemberInfo.shared.access_token
  328. if token == "" {
  329. callback(false, nil, nil)
  330. return
  331. }
  332. // 拼接 URL
  333. let urlString = KMMemberCenterConfig().activityBaseURL() + url
  334. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: params) { requestSerializer in
  335. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  336. } completion: { task, responseObject, error in
  337. guard let dict = responseObject as? [String : Any] else {
  338. callback(false, nil, error)
  339. return
  340. }
  341. let model = KMRequestResultModel(dict: dict)
  342. callback(model.isSuccess(), model, error)
  343. }
  344. }
  345. }