[swift]-AFNetworking网络封装

前端之家收集整理的这篇文章主要介绍了[swift]-AFNetworking网络封装前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1:定义一个网络工具类,如HttpTools,NetworkTools等等

在NetworkTools.swift类中:

这里采用单例封装:

import AFNetworking

// 枚举方式1
enum RequestType {
    case GET
    case POST
}

// 枚举方式2
enum RequestType1 : Int {
    case GET = 0
    case POST = 1
}

// 枚举方式3
enum RequestType2 : String {
    case GET = "GET"
    case POST = "POST"
}



class NetworkTools: AFHTTPSessionManager {

    /// let是线程安全的
    static let shareInstance : NetworkTools = {
       let tools = NetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
    }()
}

// MARK: - 封装请求方法
extension NetworkTools {
    func request(methodType : RequestType,urlString : String,parameters : [String : AnyObject],finished:(result : AnyObject?,error : NSError?) -> ()) {
        
        // 定义成功的回调闭包:使用一个常量来接收它
        let successCallBack = { (task : NSURLSessionDataTask,result : AnyObject?) in
            finished(result: result,error: nil)
        }
        
        
        // 定义一个失败的回调闭包:使用一个常量来接收它
        let failureCallBack = { (task : NSURLSessionDataTask?,error : NSError) in
            finished(result: nil,error: error)
        }
    
        // 发送网络请求
        if methodType == .GET {
            GET(urlString,parameters: parameters,progress: nil,success: successCallBack,failure: failureCallBack)
        }else {
            POST(urlString,failure: failureCallBack)
        }
    }
}

2:在viewController.swift中调用网络请求接口

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //print(NetworkTools.shareInstance)
        //print(NetworkTools.shareInstance)
    }
    
    override func touchesBegan(touches: Set<UITouch>,withEvent event: UIEvent?) {
        /// 外面请求接口回调
        NetworkTools.shareInstance.request(.POST,urlString: "http://httpbin.org/post",parameters: ["name" : "lishengbing","age" : 106]) { (result,error) in
            if error != nil {
                print(error)
                return
            }
            
            print(result)
        }
    }
    

}

知识点:

1:swift中创建单例:

class NetworkTools: AFHTTPSessionManager {

    /// let是线程安全的
    static let shareInstance : NetworkTools = {
       let tools = NetworkTools()
        return tools
    }()
}

2:swift中枚举的定义:

// 枚举方式1
enum RequestType {
    case GET
    case POST
}

// 枚举方式2
enum RequestType1 : Int {
    case GET = 0
    case POST = 1
}

// 枚举方式3
enum RequestType2 : String {
    case GET = "GET"
    case POST = "POST"
}

意见反馈邮件:1415429879@qq.com 欢迎你们的阅读和赞赏、谢谢

原文链接:https://www.f2er.com/swift/323268.html

猜你在找的Swift相关文章