Swift和OC基於AFNetworking的網路請求流程相同, 就是語法不同, 對於Swift語法不是很清楚的同學, 建議多看看API文檔, 自己多多嘗試. 寫過OC的應該都明白每句話做什麼的, 就不過多解釋了. 之前有講過如何進行混編, 所以集成AFNetworking的過程就不再贅述 ...
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("請求失敗")
})
}
}
}
這隻是基本的網路請求, 如果需要對請求頭尾進行加工, 修改下函數即可.