import UIKit
class NetRequestManager: NSObject {
enum 網(wǎng)絡(luò)請(qǐng)求類型 {
case GET請(qǐng)求
case POST請(qǐng)求
}
class func 請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)(參數(shù)1 網(wǎng)址:String,參數(shù)2 請(qǐng)求類型:網(wǎng)絡(luò)請(qǐng)求類型,參數(shù)3 POST字典:[String:String]?, 請(qǐng)求成功閉包:((成功參數(shù):NSData)->()), 請(qǐng)求失敗閉包:((失敗參數(shù):NSError)->()) ) {
let 網(wǎng)絡(luò)請(qǐng)求 = NetRequestManager()
guard let 字典內(nèi)容 = POST字典 else{
網(wǎng)絡(luò)請(qǐng)求 .GET請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)(參數(shù)1: 網(wǎng)址, 請(qǐng)求成功閉包: 請(qǐng)求成功閉包, 請(qǐng)求失敗閉包: 請(qǐng)求失敗閉包)
return
}
網(wǎng)絡(luò)請(qǐng)求.請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)(參數(shù)1: 網(wǎng)址, 參數(shù)2:請(qǐng)求類型 , 參數(shù)3: 字典內(nèi)容, 請(qǐng)求成功閉包: 請(qǐng)求成功閉包, 請(qǐng)求失敗閉包: 請(qǐng)求失敗閉包)
}
func 根據(jù)字典返回請(qǐng)求體Data(請(qǐng)求體字典:[String:String])->(NSData){
var 數(shù)組:[String] = []
for key in 請(qǐng)求體字典.keys{
let 拼接字符串 = key + "=" + 請(qǐng)求體字典[key]!
數(shù)組.append(拼接字符串)
}
let 請(qǐng)求串:String = 數(shù)組.joinWithSeparator("&")
return 請(qǐng)求串.dataUsingEncoding(NSUTF8StringEncoding)!
}
func 請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)(參數(shù)1 網(wǎng)址:String,參數(shù)2 請(qǐng)求類型:網(wǎng)絡(luò)請(qǐng)求類型,參數(shù)3 POST字典:[String:String], 請(qǐng)求成功閉包:((參數(shù):NSData)->()), 請(qǐng)求失敗閉包:((參數(shù):NSError)->()) ) {
let url = NSURL(string: 網(wǎng)址)
let request = NSMutableURLRequest.init(URL: url!)
request.timeoutInterval = 10
if(請(qǐng)求類型 == 網(wǎng)絡(luò)請(qǐng)求類型.POST請(qǐng)求){
request.HTTPMethod = "POST"
if(POST字典.count > 0){
request.HTTPBody = 根據(jù)字典返回請(qǐng)求體Data(POST字典)
}
}
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
if let 成功返回Data = data {
請(qǐng)求成功閉包(參數(shù): 成功返回Data)
}
if let 失敗返Error = error {
請(qǐng)求失敗閉包(參數(shù): 失敗返Error)
}
}
task.resume()
}
func GET請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)(參數(shù)1 網(wǎng)址:String, 請(qǐng)求成功閉包:((參數(shù):NSData)->()), 請(qǐng)求失敗閉包:((參數(shù):NSError)->()) ) {
let url = NSURL(string: 網(wǎng)址)
let request = NSMutableURLRequest.init(URL: url!)
request.timeoutInterval = 10
request.HTTPMethod = "GET"
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
if let 成功返回Data = data {
請(qǐng)求成功閉包(參數(shù): 成功返回Data)
return
}
if let 失敗返Error = error {
請(qǐng)求失敗閉包(參數(shù): 失敗返Error)
return
}
}
task.resume()
}}
https://github.com/yellowPea/learn-swift-by-create-a-swift-tableView-