iOS开发--Swift 基于AFNetworking 3.0的网络请求封装
Swift和OC基于AFNetworking的网络请求流程相同, 就是语法不同, 对于Swift语法不是很清楚的同学, 建议多看看API文档, 自己多多尝试. 写过OC的应该都明白每句话做什么的, 就不过多解释了.
之前有讲过如何进行混编, 所以集成AFNetworking的过程就不再赘述
直接上代码, 不废话,
import UIKit
class InternetDataRequeset {
//Post请求时, Body字符串转换成字典方法
//设置类型为静态方法
static func changeStringToDictionary(string : String)->NSDictionary{
let dic: NSMutableDictionary = NSMutableDictionary()
let array = string.componentsSeparatedByString("&")
for str : String in array{
let tempArray = str.componentsSeparatedByString("=")
dic.setObject(tempArray[1], forKey: tempArray[0])
}
return dic
}
//静态网络请求方法, GET请求, POST请求均适用, POST需要参数字典, 可由上一个方法获得
//urlString: 网络请求链接字符串
//bodyDic: Post请求参数字典(可选类型)
//data()->(): 闭包函数, 基本等价于OC中的block, 用于数据的回调.
static func getDataByString(var urlString urlSting: String, bodyDic: NSDictionary!, data: (data: AnyObject) -> ()){
//字符串的转码
urlSting = urlSting.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
//创建管理者对象
let manager = AFHTTPSessionManager()
//设置允许请求的类别
manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/plain", "text/json", "application/json","text/javascript","text/html", "application/javascript", "text/js") as? Set<String>
//开始请求
if bodyDic == nil {
manager.GET(urlSting, parameters: nil, progress: { (downloadProgress: NSProgress) -> Void in
}, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
data(data: responseObject!)
}, failure: { (task: NSURLSessionDataTask?, error : NSError) -> Void in
print("请求失败")
})
}
else{
manager.POST(urlSting, parameters: bodyDic, progress: { (downloadProgress: NSProgress) -> Void in
}, success: { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
data(data :responseObject!)
}, failure: { (task: NSURLSessionDataTask?, error : NSError) -> Void in
print("请求失败")
})
}
}
}
这只是基本的网络请求, 如果需要对请求头尾进行加工, 修改下函数即可.