iOS开发:Swift AFNetworking 3.0使用示例

封装了个HttpManager,通过AFNetworking处理http请求,AFNetworking 3.0已经废弃POST和GET方法,因为SwiftyJSON可以直接将NSData作为参数,没有返回没有转换成String,String只用于debug输出,可注释掉,减少性能浪费。
HttpManager.swift:

import AFNetworking

class HttpManager {
    let  manager = AFHTTPSessionManager()
    private static let httpManager: HttpManager = HttpManager()
    
    static var sharedInstance:HttpManager {
        return httpManager
    }
    private init() {
        manager.responseSerializer = AFHTTPResponseSerializer()
        manager.responseSerializer.acceptableContentTypes?.insert("text/html")
        manager.requestSerializer.timeoutInterval = 10
    }
    
    /// Http Get方法,不带参数
    /// - parameter url: 请求的URL
    /// - parameter success: 成功后回调的闭包
    /// - parameter encoding: 编码,默认utf-8
    func get(url: String,encoding:UInt = NSUTF8StringEncoding,success:((NSData) -> Void)?, failure: ((NSError) -> Void)?) {
        return get(url, encoding: encoding, params: nil, success: success, failure: failure)
    }
    
    /// Http Get方法
    /// - parameter url: 请求的URL
    /// - parameter success: 成功后回调的闭包
    /// - parameter encoding: 编码,默认utf-8
    /// - parameter params: 参数,拼到url后缀里
    func get(url: String,encoding:UInt = NSUTF8StringEncoding,params: [String: AnyObject]?,success:((NSData) -> Void)?, failure: ((NSError) -> Void)?) {
        return request(url, method: "GET", encoding: encoding, params: params, success: success, failure: failure)
    }
    
    /// Http Post方法
    /// - parameter url: 请求的URL
    /// - parameter success: 成功后回调的闭包
    /// - parameter encoding: 编码,默认utf-8
    /// - parameter params: Post 参数
    func post(url: String,encoding:UInt = NSUTF8StringEncoding,params: [String: AnyObject]?, success:((NSData) -> Void)?, failure: ((NSError) -> Void)?) {
        return request(url, method: "POST", encoding: encoding, params: params, success: success, failure: failure)
    }
    
    ///发送请求
    /// - parameter url: 请求URL
    /// - parameter method: 请求方法
    /// - parameter encoding: 编码,默认utf-8
    /// - parameter params:参数,如果是get,会添加到url后缀
    /// - parameter success: 成功回调闭包
    /// - parameter failure: 失败回调
    func request(url: String, method: String = "GET",encoding:UInt = NSUTF8StringEncoding,params: [String: AnyObject]?, success:((NSData) -> Void)?, failure: ((NSError) -> Void)?) {
        
        let paramStr = NSMutableString()
        for (key,value) in params! {
            paramStr.appendString("\(key)=\(value)&")
        }
        var requestUrl = url;
        if(method == "GET") {
            requestUrl = "\(url)?\(paramStr)"
        }

        let urlRequest=NSMutableURLRequest(URL: NSURL(string: requestUrl)!)
        urlRequest.HTTPMethod = method
        urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
        
        if method == "POST" {
            let bodyData = paramStr.stringByAddingPercentEscapesUsingEncoding(encoding)?.dataUsingEncoding(encoding)
            urlRequest.HTTPBody = bodyData
        }

        let task = manager.dataTaskWithRequest(urlRequest) { (response, responseObj, error) -> Void in
            if (error != nil) {
                failure!(error!)
                return
            }
            let responseData = responseObj as! NSData
            let responseStr = NSString(data: responseData, encoding: encoding)
            PLog.v(responseStr!)
            success!(responseData)
        }
        task.resume()
    }

© 2016, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记