首先怎么下载框架我这里就不说了,进入正题!
首先创建一个NewworkingTools文件
import AFNetworking
//定义枚举类型
enum RequestType : String {
case GET = "GET"
case POST = "POST"
}
class NetworkTools: AFHTTPSessionManager {
//单例
static let shareInstance :NetworkTools = {
let tools = NetworkTools()
//这是给JSON序列化加一个格式
tools.responseSerializer.acceptableContentTypes?.insert("text/html")
return tools
}()
}
// MARK:- 封装请求方法
extension NetworkTools {
func request(methodType : RequestType , urlString : String,parameters :[String : AnyObject],failure :(result : AnyObject? , error : NSError?) -> ()) {
//判断是那种请求 GET
if methodType == .GET{
GET(urlString, parameters: parameters, progress: nil, success: { (stak : NSURLSessionDataTask ,result : AnyObject?) -> Void in
print(result)
}, failure: { (task :NSURLSessionDataTask?, error:NSError?) -> Void in
})
}
else //POST
{
POST(urlString, parameters: parameters, progress: nil, success: { (stak : NSURLSessionDataTask, result : AnyObject?) -> Void in
}, failure: { (task : NSURLSessionDataTask?, error : NSError?) -> Void in
})
}
}
}
}
现在可以在外面试着调用了
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
NetworkTools.shareInstance.request(.GET, urlString: "http://httpbin.org/get", parameters: ["name":"MarkTang"]) { (result, error) -> () in
}
}
如果你没有改配置的话,会出现以下错误
你需要需要以下info的配置,因为是可能是https
再次运行,你会拿到类似于以下数据
接下来在继续优化一下代码
// MARK:- 封装请求方法
extension NetworkTools {
func request(methodType : RequestType , urlString : String,parameters :[String : AnyObject],failure :(result : AnyObject? , error : NSError?) -> ()) {
//1.定义成功回调的闭包
let successCallBack = { (stak : NSURLSessionDataTask ,result : AnyObject?) -> Void in
//把闭包传出去
failure(result: result, error: nil)
}
//2.定义失败的回调闭包
let failureCallBack = { (stak : NSURLSessionDataTask? ,error : NSError?) -> Void in
//把闭包传出去
failure(result: nil, error: error)
}
//3.判断是那种请求 GET 发送请求
if methodType == .GET{
GET(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}
else //POST
{
POST(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}
}
}
//在外面可以拿到返回的值
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
NetworkTools.shareInstance.request(.GET, urlString: "http://httpbin.org/get", parameters: ["name":"MarkTang"]) { (result, error) -> () in
if error != nil {
print(error)
return
}
print(result)
}
}