swift我的Swift开发iOS开发精进

拿走即用之AFN封装(Swift版)

2016-03-11  本文已影响2178人  鹿丸眼中的云

AFN封装

关于Swift使用Cocospods是否添加桥接文件

代码

import UIKit
import AFNetworking


/// 请求方法
///
/// - GET:  get
/// - POST: post
enum WHRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class WHNetworkTools: AFHTTPSessionManager {
    
    // 单例
    static let sharedTools: WHNetworkTools = {
        let instance = WHNetworkTools()
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    // (response: AnyObject?, error: NSError?)->()
    // 定义请求完成的回调的别名
    typealias WHRequestCallBack = (response: AnyObject?, error: NSError?)->()
    
    /// 请求数据
    ///
    /// - parameter urlString:  请求地址
    /// - parameter parameters: 请求参数
    /// - parameter finished:   请求成功或者失败的回调
    func request(method: WHRequestMethod = .GET, urlString: String, parameters: AnyObject?, finished:WHRequestCallBack){
        
        // dataTaskWithHttp 是写在 .m 文件里面的
        // 对应在 Swift 中的,就是 private 修饰的方法
        
        // 定义请求成功的闭包
        let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            finished(response: responseObject, error: nil)
        }
        
        // 定义请求失败的闭包
        let failure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(response: nil, error: error)
        }
        
        if method == .GET {
            
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
    
    /// 发送请求(上传文件)

    func requestWithData(data: NSData, name: String, urlString: String, parameters: AnyObject?, finished:WHRequestCallBack) {
        // 定义请求成功的闭包
        let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            finished(response: responseObject, error: nil)
        }
        
        // 定义请求失败的闭包
        let failure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(response: nil, error: error)
        }
        
        POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            formData.appendPartWithFileData(data, name: name, fileName: "aa", mimeType: "application/octet-stream")
        }, progress: nil, success: success, failure: failure)
    }
}
上一篇下一篇

猜你喜欢

热点阅读