1.在viewcotroller中写入方法
func getAFNetWorkingJsonData(channel:String) -> Void {
var urlString = "http://api.jisuapi.com/news/get?channel=\(channel)&start=0&num=10&appkey=de394933e1a3e2db"
urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!
NetworkTools.shareInstance.request(methodType: .GET, urlString: urlString, parameters: ["":"" as AnyObject]) { (jsonData, error) in
if error != nil {
print(error!)
return
}
print(jsonData!)
}
2.创建一个类封装
// 定义枚举类型
enum HTTPRequestType : Int{
case GET = 0
case POST
}
class NetworkTools: AFHTTPSessionManager {
// 设计单例 let是线程安全的
static let shareInstance : NetworkTools = {
let tools = NetworkTools()
tools.responseSerializer.acceptableContentTypes?.insert("text/html")
return tools
}()
}
// 封装请求方法
extension NetworkTools {
func request(methodType : HTTPRequestType, urlString : String, parameters : [String : AnyObject], finished :@escaping (_ result : AnyObject?, _ error : Error?)-> ()) {
// 1 成功回调
let successCallBack = {(task :URLSessionDataTask, result : Any) in
finished(result as AnyObject?, nil)
}
// 2 失败回调
let failureCallBack = {(task : URLSessionDataTask?, error :Error) in
finished(nil, error)
}
if methodType == .GET {
// get请求
get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}else {
// post请求
post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
}
}
}