美文网首页
swift Al 网络封装

swift Al 网络封装

作者: 我会回来的 | 来源:发表于2023-05-18 14:28 被阅读0次

    Alamofire:网络封装

    代码如下: 

    //

    //  NetRequestManager.swift

    //  Alamoire

    //

    //  Created by Mac on 2023/5/18.

    //

    importFoundation

    importAlamofire

    class NetRequestManager : NSObject {

        ///成功回调

        typealiasSuccessHandlerType= (([String:Any],Int) ->Void)

        ///失败回调

        typealias FailureHandlerType = ((MiruairNetError) -> Void)

        ///请求类型

        privatevarrequestType:HTTPMethod= .post

        ///  URL

        private var url: String?

        ///  参数

        privatevarparams: [String:Any]?

        ///  成功的回调

        private var success: SuccessHandlerType?

        ///  失败的回调

        private var failure: FailureHandlerType?

        ///  headers 设置

        private var headers: HTTPHeaders?

        ///  数据请求

        private var httpRequest: DataRequest?

        ///  链式语法

        funcurl(_url:String?) ->Self{

            self.url= url ??""

            return self

        }

        ///  请求类型

        funcrequestType(_type:HTTPMethod) ->Self{

            self.requestType= type

            return self

        }

        ///请求参数

        funcparams(_params: [String:Any]?) ->Self{

            self.params= params

            return self

        }

        ///成功

        funcsuccess(_handler:@escapingSuccessHandlerType) ->Self{

            self.success= handler

            return self

        }

        ///失败

        funcfailed(_handler:@escapingFailureHandlerType) ->Self{

            self.failure= handler

            return self

        }

        ///获取包头

        funcgetHeader() ->HTTPHeaders{

            varrequestHeader =HTTPHeaders()

            ifletheader =headers{

                requestHeader = header

            }else{

                requestHeader.add(name:"Conatent-Type",value:"application/json")

                requestHeader.add(name:"Accept",value:"application/json")

            }

            returnrequestHeader

        }

        ///开始请求

        funcstartRequest() ->Request? {

            letrequestHeaders =getHeader()

            ///不使用缓存

            AF.sessionConfiguration.requestCachePolicy = .reloadIgnoringCacheData

            AF.sessionConfiguration.timeoutIntervalForRequest = 30

            ///  interceptor :      requestModifier:

            httpRequest = AF.request(self.url!,method: self.requestType,parameters: self.params,encoding: URLEncoding(destination: .queryString),headers: requestHeaders,interceptor: nil,requestModifier: nil)

            _ =httpRequest?.id

            httpRequest?.responseString(encoding:.utf8,completionHandler: { string in

                print("=======2")

                self.completeHandle(string: string)

            })

            return httpRequest

        }

        /// 请求response完成处理

        func completeHandle(string: AFDataResponse<String>) {

            letresponseResult = string.result

            varresultFlag =false

            varerrorCodeStr ="0"

            varstatusCode = string.response?.statusCode??0

            varerrorResponseMsg = string.error?.localizedDescription??""

            vartimeOut = string.error?._code

            letresultValue = string.value??""

            varserverDict =self.converStringToMap(fromStr: resultValue)

            switchresponseResult {

            case.success:

                resultFlag =true

                break

            case.failure:

                resultFlag =false

                ifletunderyingError = string.error?.asAFError?.underlyingError{

                    ifleturlError = underyingErroras?URLError{

                        switchurlError.code{

                        case.timedOut:

                            statusCode = urlError.code.rawValue

                        case.cannotConnectToHost:

                            statusCode = urlError.code.rawValue

                        case.cannotFindHost:

                            statusCode = urlError.code.rawValue

                        case.unsupportedURL:

                            statusCode = urlError.code.rawValue

                        default:

                            break

                        }

                    }

                }

                break

            default:

                break

            }

            ifstatusCode ==200{

                ifletsuclock =self.success{

                    suclock(serverDict,statusCode)

                }

            }else{

                leterrorModel =MiruairNetError.init()

                errorModel.responseErrorType= .failType

                ifleterrorBlock =self.failure{

                    errorModel.responseStatusCode= statusCode

                    errorModel.errResponseMsg= errorResponseMsg

                    errorModel.errReaponseCode= errorCodeStr

                    errorBlock(errorModel)

                }

            }

        }

        func converStringToMap(fromStr: String = "") -> [String:Any] {

            letserverData = fromStr.data(using:String.Encoding.utf8)

            do{

                letserverDict =tryJSONSerialization.jsonObject(with: serverData!,options:JSONSerialization.ReadingOptions.mutableContainers)as? [String:Any]

                returnserverDict!

            }catch{

                return[String:Any]()

            }

        }

    }

    extension NetRequestManager {

        class func getRequest(url:String,params:[String:Any] = [:],successBlock:SuccessHandlerType!,failBlock: FailureHandlerType!) ->Request? {

            returnNetRequestManager().url(url).requestType(.get).success(successBlock).failed(failBlock).startRequest()

        }

    }

    class MiruairNetError: NSObject {

        var responseStatusCode: Int = 0

        var responseStatusCodeStr: String = ""

        var errResponseMsg: String = ""

        var errReaponseCode: String = ""

        var errReaponseTimeOutCode: Int = 0

        var responseErrorType: NetResponseErrorType?

    }

    enum NetResponseErrorType: Int {

        case successType,failType

    }

    使用: 

    NetRequestManager.getRequest(url: "需要请求的url") { succeseResponse,responseCode in

               print(succeseResponse,responseCode) 

            } failBlock: { MiruairNetError in

         }

    相关文章

      网友评论

          本文标题:swift Al 网络封装

          本文链接:https://www.haomeiwen.com/subject/hleisdtx.html