首页 > 代码库 > ios开发之--swift下AFNetworking的使用
ios开发之--swift下AFNetworking的使用
1,首先使用cocoapods导入,如果有不会的同学,可以去看我写的关于cocopods使用的那篇博客
2,直接上代码:
import UIKit import AFNetworking //枚举定义请求方法 enum HTTPRequestType{ case GET case POST } class AFNetTools: AFHTTPSessionManager { //单例类 static let shareInstance : AFNetTools = { let toolInstance = AFNetTools() toolInstance.responseSerializer.acceptableContentTypes?.insert("text/html") return toolInstance }() /// 封装GET和POST 请求 /// /// - Parameters: /// - requestType: 请求方式 /// - urlString: urlString /// - parameters: 字典参数 /// - completion: 回调 func request(requestType: HTTPRequestType, urlString: String, parameters: [String: AnyObject]?, completion: @escaping (AnyObject?) -> ()) { //成功回调 let success = { (task: URLSessionDataTask, json: Any)->() in completion(json as AnyObject?) } //失败回调 let failure = { (task: URLSessionDataTask?, error: Error) -> () in print("网络请求错误 \(error)") completion(nil) } if requestType == .GET { get(urlString, parameters: parameters, progress: nil, success: success, failure: failure) } else { post(urlString, parameters: parameters, progress: nil, success: success, failure: failure) } } // 将成功和失败的回调分别写在两个逃逸闭包中 func request(requestType : HTTPRequestType, url : String, parameters : [String : Any], succeed : @escaping([String : Any]?) -> (), failure : @escaping(Error?) -> ()) { // 成功闭包 let successBlock = { (task: URLSessionDataTask, responseObj: Any?) in succeed(responseObj as? [String : Any]) } // 失败的闭包 let failureBlock = { (task: URLSessionDataTask?, error: Error) in failure(error) } // Get 请求 if requestType == .GET { get(url, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock) } // Post 请求 if requestType == .POST { post(url, parameters: parameters, progress: nil, success: successBlock, failure: failureBlock) } } }
以上就是二次封装的请求类
3,调用:
@IBAction func startRequest(_ sender: Any) { let paramerts = [ "opt_type": 1, "size" : 50, "offset" : 50 ] AFNetTools.shareInstance.request(requestType: .GET, url: "http://apiv2.yangkeduo.com/operation/15/groups", parameters: paramerts, succeed: { (response) in guard let dicArray = response?["goods_list"] as? [[String: Any]] else { return } print(dicArray) }) { (error) in guard let error = error else { return } print(error) } }
打印如下:
ios开发之--swift下AFNetworking的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。