//
// AFNetworkingManager.swift
// swift-AFNetworking
//
// Created by HMC on 16/8/9.
// Copyright © 2016年 SKing. All rights reserved.
//
import AFNetworking
//自定义枚举类型
enum RequestType {
case GET //get请求
case POST //post请求
case DOWNLOAD //下载请求
case UPLOAD //上传请求
}
class AFNetworkingManager: AFHTTPSessionManager {
//单例模式 使用闭包对实例进行值设定
static let shareObject : AFNetworkingManager = {
let manager = AFNetworkingManager()
//对于 set 对象可以进行 insert 方法进行设定值
manager.responseSerializer.acceptableContentTypes? = ["text/html","text/plain","application/json"]
return manager
}()
}
extension AFNetworkingManager {
/**
请求数据函数
- parameter requestType: 请求类型
- parameter urlString: 请求 url
- parameter parameters: 请求字典参数
- parameter returnData: 请求返回的闭包 用于数据回调
*/
func requestData(requestType: RequestType , urlString :String , parameters :[String : AnyObject]?,returnData : (result : AnyObject?,error : NSError?)->()) {
//去除 URL 中的ASSIC 码
let urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
print(urlString)
//请求成功闭包
let success = { (task : NSURLSessionDataTask,result : AnyObject?) in
print(result)
returnData(result: result,error: nil)
}
//请求失败闭包
let failure = { (task : NSURLSessionDataTask?,error : NSError) in
print(error)
returnData(result: nil, error: error)
}
if requestType == .GET {//get 类型请求
GET(urlString, parameters: parameters,progress : nil, success: success , failure: failure)
} else if requestType == .POST{//post 类型请求
POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
} else if requestType == .DOWNLOAD {//下载 类型请求
} else if requestType == .UPLOAD {//上传 类型请求
}
}
}
调用例子 AFNetworkingManager.shareObject.requestData()
//get 请求
AFNetworkingManager.shareObject.requestData(.GET, urlString: "http://httpbin.org/get", parameters: ["name" : "SongJinwei","age" : 25]) { (result, error) in
print(result)
}
//post 请求
AFNetworkingManager.shareObject.requestData(.POST, urlString: "http://httpbin.org/post", parameters: ["name" : "SongJinwei","age" : 25]) { (result, error) in
print(result)
}