Swift3下基于AFNetworking的网络请求封装
//
// DifferBaseNetwork.swift
// AppGame
//
// Created by zengchunjun on 2017/7/7.
// Copyright © 2017年 zengchunjun. All rights reserved.
//
import UIKit
//枚举,swift3后 官方用小写、我们可以模仿苹果
public enum RequestType {
case get
case post
}
@objc class DifferBaseNetwork: AFHTTPSessionManager {
//有多个baseURL可以通过继承在子类中进行设置单例
static let shareInstance : DifferBaseNetwork = {
let tools = DifferBaseNetwork()
// let tools = DifferBaseNetwork(baseURL: <#T##URL?#>)
return tools
}()
}
extension DifferBaseNetwork{
// 第一个 _ 代表第一个参数没有参数标签 @escaping代表逃逸闭包的意思
// @escaping 逃逸闭包:闭包在函数执行完后才被调用,调用的地方超过了这个函数的范围,所有叫逃逸闭包
//不带进度的请求
public func request(_ methodType : RequestType , urlString : String , parameters : inout [String : Any],completed : @escaping (Any?,Error?)->() ) -> Void {
/*
if methodType == .get {
get(urlString, parameters: parameters, progress: nil, success: { (task, responseObj) in
completed(responseObj,nil)
}, failure: { (task, error) in
completed(nil,error)
})
}else if methodType == .post{
post(urlString, parameters: parameters, progress: nil, success: { (task, respostObj) in
completed(respostObj,nil)
}, failure: { (task, error) in
completed(nil,error)
})
}
*/
//对于具体中的项目请求,有时我们需要传递额外的信息,例如:将版本号、设备信息、设备唯一标识等信息 放进 字典的 extra 键中,因此,我们就需要 传递进来的参数 ,所有需要 标识为 输入输入 参数 inout.对于没有该要求的可去掉 inout 关键词
parameters["extra"] = DiffUtil.differRequestExtra()
//成功闭包
let successBlock = {(task : URLSessionDataTask , responseObj : Any?) in
completed(responseObj,nil)
}
//失败闭包
let failureBlock = { (task : URLSessionDataTask? , error : Error?) in
completed(nil,error)
}
if methodType == .get {
get(urlString, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)
}else if methodType == .post{
post(urlString, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock)
}
}
//带进度
public func requestWithProgress(_ methodType : RequestType, urlString : String,parameters : inout [String : Any] , progress : @escaping (_ progess : Progress)->() , completed : @escaping (_ responseObj : Any?,_ error : Error?)->()) -> Void {
parameters["extra"] = DiffUtil.differRequestExtra()
//成功闭包
let successBlock = {(task : URLSessionDataTask , responseObj : Any?) in
completed(responseObj,nil)
}
//失败闭包
let failureBlock = { (task : URLSessionDataTask? , error : Error?) in
completed(nil,error)
}
//进度闭包
let progress = { (prog : Progress) in
progress(prog)
}
if methodType == .get {
get(urlString, parameters: parameters, progress: progress, success: successBlock, failure: failureBlock)
}else if methodType == .post{
post(urlString, parameters: parameters, progress: progress, success: successBlock, failure: failureBlock)
}
}
}