Swift之AFNetworking简单封装

前言

 对于开发者来说,网络请求是必不可少的一个重要环节,每请求一个接口都需要进行数据请求,那么封装网络库是尤为重要的,如今主流的三方网络框架属AFNetworking,它的使用极大的简化了原生的网络请求方式,方便、快捷,使得广大开发者的首选。> 看到网上好多都是关于OC的AFNetworking简单封装,最近刚好有时间整理博客,我就简单封装了一下Swift版本的AFNetworking(基于3.0以上)。

cocoapods集成AFNetworking

注: cocoapods集成AFNetworking的具体过程,在这里不一一展示,具体内容,请查看另一篇内容【cocopods集成】"https://blog.csdn.net/macro_sn/article/details/81744433"

废话不多说,直接上代码:

import UIKit

importAFNetworking

// requet type

enumHTTPMethod {

    caseGET

    casePOST

}

/**

 *  An API structure is defined to define various network interfaces.

 */

struct API {

    // Define hostname

    staticlethostName =""

    // Define baseURL

    staticletbaseURL =""

}

class AppService: AFHTTPSessionManager {

     staticletshareInstance:AppService= {

        letmanager =AppService()

        manager.requestSerializer = AFJSONRequestSerializer()

        let setArr = NSSet(objects: "text/html", "application/json", "text/json")

        manager.responseSerializer.acceptableContentTypes = setArr as? Set

        // add HttpHeader

        manager.requestSerializer.setValue("application/json", forHTTPHeaderField:"Content-Type")

        manager.requestSerializer.setValue("application/json", forHTTPHeaderField:"Accept")

        manager.requestSerializer.willChangeValue(forKey:"timeoutInterval")

        manager.requestSerializer.timeoutInterval = 30.0

        manager.requestSerializer.didChangeValue(forKey:"timeoutInterval")

        returnmanager

    }()


    /**

     A method of opening to the outside world is defined to make requests for network data.


     - parameter methodType:        request type(GET / POST)

     - parameter urlString:        url address

     - parameter parameters:

                                    The parameter required to send a network                  request is a dictionary.


     - parameter resultBlock:      The completed callback.


     - parameter responseObject:    Callback parameters to return the requested  data.


     - parameter error:            If the request succeeds, then the error is nil.


     */

    funcrequest(methodType:HTTPMethod, urlString:String, parameters: [String:AnyObject]?, resultBlock:@escaping(Any?,Error?)->()) {


        // If the request succeeds, then the error is nil.

        letsuccessBlock = { (task:URLSessionDataTask, responseObj:Any?)in

            resultBlock(responseObj,nil)

        }


        // If the request succeeds, then the error is nil.

        letfailureBlock = { (task:URLSessionDataTask?, error:Error)in

            resultBlock(nil, error)

        }


        // request type

        ifmethodType ==HTTPMethod.GET{


            get(urlString, parameters: parameters, progress:nil, success: successBlock, failure: failureBlock)

        }else{

            post(urlString, parameters: parameters, progress:nil, success: successBlock, failure: failureBlock)

        }

    }

}

你可能感兴趣的:(Swift之AFNetworking简单封装)