美文网首页
Swift之AFNetworking简单封装

Swift之AFNetworking简单封装

作者: 饿狼开发 | 来源:发表于2018-08-21 15:56 被阅读67次

    前言

     对于开发者来说,网络请求是必不可少的一个重要环节,每请求一个接口都需要进行数据请求,那么封装网络库是尤为重要的,如今主流的三方网络框架属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简单封装

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