swift5.0 封装Alamofire

swfit5.0使用网络请求框架Alamofire的简单封装

完整代码如下

//

//  NotoceSwiftNetWorkTools.swift

//  NoticeXi

//

//  Created by li lei on 2022/5/11.

//  Copyright © 2022 zhaoxiaoer. All rights reserved.

//

import UIKit

import Alamofire

//闭包回调

public typealias Success = (_ data : Data)->()

public typealias Failure = (_ error : Error)->()

class NotoceSwiftNetWorkTools: NSObject {

    

    //单例

    @objc static var sharedInstance : NotoceSwiftNetWorkTools {

        struct Static {

            static let instance : NotoceSwiftNetWorkTools = NotoceSwiftNetWorkTools()

        }

        return Static.instance

    }

    

    //get请求

    func getRequest(

        _ urlString:String,

        params:Parameters? = nil,

        _ Accept:String,

        success: @escaping Success,

        failure: @escaping Failure

    )

    {

        request(urlString, Accept, params: params, method: .get, success, failure)

    }

    

    //post请求

    func postRequest(

        _ urlString:String,

        params:Parameters? = nil,

        _ Accept:String,

        success: @escaping Success,

        failure: @escaping Failure

    )

    {

        request(urlString, Accept, params: params, method: .get, success, failure)

    }

    

    //公共的私有方法

    private func request(

        _ urlString: String,

        _ Accept:String,

        params: Parameters? = nil,

        method: HTTPMethod,

        _ success: @escaping Success,

        _ failure: @escaping Failure)

    {

        let manager = Alamofire.SessionManager.default

        manager.session.configuration.timeoutIntervalForRequest = 30

                

        var headers: HTTPHeaders = [

            "Content-Type":"application/x-www-form-urlencoded",

            "Lang":"cn",

            "Accept": Accept

        ]

        

        let tokenStr = NoticeSaveModel.getToken() as NSString

        

        if tokenStr.length > 5{

           headers["Authorization"] = "Bearer " + NoticeSaveModel.getToken()

        }

        

        

        manager.request(BASE_URL + urlString, method: method, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in

            guard response.result.isSuccess else { return }

            if let value = response.result.value {

                let json = JSON(value);

                print(json)

            }

        }​​​​​​​

 

    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值