123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- //
- // NetworkManager.swift
- // iOSFirst
- //
- // Created by 孙宇峰 on 2023/2/22.
- //
-
- import Foundation
- import Moya
- import Alamofire
- import SwiftyJSON
-
- /// 超时时长
- private var requestTimeOut:Double = 30
- ///endpointClosure
- private let myEndpointClosure = { (target: AccountService) -> Endpoint in
- ///这里的endpointClosure和网上其他实现有些不太一样。
- ///主要是为了解决URL带有?无法请求正确的链接地址的bug
- let url = target.baseURL.absoluteString + target.path
- var endpoint = Endpoint(
- url: url,
- sampleResponseClosure: { .networkResponse(200, target.sampleData) },
- method: target.method,
- task: target.task,
- httpHeaderFields: target.headers
- )
- switch target {
- default:
- requestTimeOut = 30//设置默认的超时时长
- return endpoint
- }
- }
-
- private let requestClosure = { (endpoint: Endpoint, done: MoyaProvider.RequestResultClosure) in
- do {
- var request = try endpoint.urlRequest()
- //设置请求时长
- request.timeoutInterval = requestTimeOut
- // 打印请求参数
- if let requestData = request.httpBody {
- log.info("\(request.url!)"+"\n"+"\(request.httpMethod ?? "")"+"发送参数"+"\(String(data: request.httpBody!, encoding: String.Encoding.utf8) ?? "")")
- }else{
- log.info("\(request.url!)"+"\(String(describing: request.httpMethod))")
- }
- done(.success(request))
- } catch {
- done(.failure(MoyaError.underlying(error, nil)))
- }
- }
-
- /* 设置ssl
- let policies: [String: ServerTrustPolicy] = [
- "example.com": .pinPublicKeys(
- publicKeys: ServerTrustPolicy.publicKeysInBundle(),
- validateCertificateChain: true,
- validateHost: true
- )
- ]
- */
-
- // 用Moya默认的Manager还是Alamofire的Manager看实际需求。HTTPS就要手动实现Manager了
- //private public func defaultAlamofireManager() -> Manager {
- //
- // let configuration = URLSessionConfiguration.default
- //
- // configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
- //
- // let policies: [String: ServerTrustPolicy] = [
- // "ap.grtstar.cn": .disableEvaluation
- // ]
- // let manager = Alamofire.SessionManager(configuration: configuration,serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies))
- //
- // manager.startRequestsImmediately = false
- //
- // return manager
- //}
-
-
- /// NetworkActivityPlugin插件用来监听网络请求
- private let networkPlugin = NetworkActivityPlugin.init { (changeType, targetType) in
-
- log.info("networkPlugin \(changeType)")
- //targetType 是当前请求的基本信息
- switch(changeType){
- case .began:
- log.info("开始请求网络")
-
- case .ended:
- log.info("结束")
- }
- }
-
- // https://github.com/Moya/Moya/blob/master/docs/Providers.md 参数使用说明
- //stubClosure 用来延时发送网络请求
-
- let accountProvider = MoyaProvider<AccountService>(endpointClosure: myEndpointClosure, requestClosure: requestClosure, plugins: [networkPlugin], trackInflights: false)
|