最近項(xiàng)目上Swift, 所以沒(méi)有采用AFN作網(wǎng)絡(luò)框架來(lái)使用, 即便可以使用OC轉(zhuǎn)Swift利用 AFN,但個(gè)人覺(jué)得 得學(xué)點(diǎn)新東西,要不項(xiàng)目就白做了. 所以使用AFN同一團(tuán)隊(duì)開(kāi)發(fā)的 Alamofire進(jìn)行Swift開(kāi)發(fā).
Alamofire 使用:
- 和AFN一樣 作者并不希望我們直接使用 本類來(lái)操作, 建議建立網(wǎng)絡(luò)工具類, 繼承于它,然后設(shè)置單例, 這樣, 使用單例也就是使用 AFN框架. 這種方式便于我們做后期的修改
對(duì)于無(wú)論AFN和Alamofire設(shè)置單例都很簡(jiǎn)單, 應(yīng)為你本身調(diào)用的manager 就是一個(gè)單例, 所以你只需簡(jiǎn)單的做一層包裝,就是調(diào)用了單例
這里我們 使用 static關(guān)鍵字, 全局量,只產(chǎn)生一份內(nèi)存
// 單例
static let shareInstance: NetworkTools = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return NetworkTools(configuration: configuration)
}()
- 說(shuō)真的我對(duì)于 Alamofire 就會(huì)使用一個(gè)方法,就是
request(...){...}
這里我就說(shuō)一下使用,和AFN一個(gè) 對(duì)于網(wǎng)絡(luò)請(qǐng)求我們有 GET 和 POST 兩種請(qǐng)求方式. 但是對(duì)于 Alamofire這兩種方式我們只需要進(jìn)行一個(gè)函數(shù)就可以實(shí)現(xiàn)了, Swift很支持函數(shù)的 重寫(xiě), 函數(shù)響應(yīng)式編程思想,
這里我簡(jiǎn)單的 將我寫(xiě)的函數(shù) 進(jìn)行貼出來(lái), 各位看官 不要見(jiàn)笑
// 登陸狀態(tài)回調(diào), 確定是否為已經(jīng)正常登陸上了
func loginXQT(username name: String,
password code: String,
finish:(dict: [String: AnyObject]?, error: NSError?) -> ()){
SVProgressHUD.setMinimumDismissTimeInterval(1.0)
SVProgressHUD.showWithStatus("正在登陸")
SVProgressHUD.setDefaultMaskType(.Black)
// 1. 準(zhǔn)備路徑
let path = "mUserLogin.htm"
// 2. 設(shè)置參數(shù)
let parameter = ["userLogingName": name , "userLogingCode": code]
/**
* 這里 需要學(xué)習(xí)的事, Alamofire 充分利用了 響應(yīng)式 函數(shù)編程 原理. 將所有的 響應(yīng)過(guò)程模塊化, 前者的響應(yīng) 剛好是后者的 調(diào)用者. .... 這里我也不是 很好的理解 ,
request , 創(chuàng)建請(qǐng)求
responseJson ,對(duì)請(qǐng)求 進(jìn)行 執(zhí)行, 產(chǎn)生 數(shù)據(jù)交互
所有的 結(jié)果存儲(chǔ)在 response 中 . result. 結(jié)果集中存儲(chǔ) 成功與否, 數(shù)據(jù)有無(wú)
*/
request(.POST, baseURL + path, parameters: parameter).responseJSON { (response) -> Void in
if response.result.isSuccess
{
SVProgressHUD.showSuccessWithStatus("登陸成功")
finish(dict: response.result.value as? [String : AnyObject], error: nil)
}else{
SVProgressHUD.showErrorWithStatus("登陸失敗,請(qǐng)檢查網(wǎng)絡(luò)")
finish(dict: nil, error: response.result.error)
}
}
}
這里利用了函數(shù)響應(yīng)式編程思想, 由request()函數(shù)
引出,響應(yīng)responseJson{內(nèi)部是個(gè)閉包}
, 這里就是簡(jiǎn)單的思想, 前一個(gè)函數(shù)返回第二個(gè)函數(shù)的調(diào)用者, 然后直接調(diào)用,.
返回值 response 的類型是 Response<AnyObject, NSError>
一個(gè)結(jié)構(gòu)體, 內(nèi)部包含
public struct Response<Value, Error: ErrorType> {
// 關(guān)于響應(yīng)的請(qǐng)求體
public let request: NSURLRequest?
// 響應(yīng)體
public let response: NSHTTPURLResponse?
// 響應(yīng)數(shù)據(jù)
public let data: NSData?
// 響應(yīng)結(jié)果 --> 我們想要的數(shù)據(jù)
public let result: Result<Value, Error>
public init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>) {
self.request = request
self.response = response
self.data = data
self.result = result
}
}
```objc
public enum Result<Value, Error: ErrorType> {
case Success(Value)
case Failure(Error)
/// Returns `true` if the result is a success, `false` otherwise.
// 文檔中指出, 如果確定 結(jié)果已成功請(qǐng)求, 則返回 true ,如果請(qǐng)求失敗則是 false
public var isSuccess: Bool {
switch self {
case .Success:
return true
case .Failure:
return false
}
}
/// Returns `true` if the result is a failure, `false` otherwise.
public var isFailure: Bool {
return !isSuccess
}
/// Returns the associated value if the result is a success, `nil` otherwise.
// 文檔中指出, 如果請(qǐng)求成功的話 , 就會(huì)返回 對(duì)應(yīng)關(guān)聯(lián)的返回結(jié)果
// 這里結(jié)果我們所獲取的就是 對(duì)應(yīng)的 數(shù)據(jù)庫(kù) 請(qǐng)求的 返回?cái)?shù)據(jù)
public var value: Value? {
switch self {
case .Success(let value):
return value
case .Failure:
return nil
}
}
/// Returns the associated error value if the result is a failure, `nil`
otherwise.
// 文檔中指出, 請(qǐng)求失敗的話返回 error 的 錯(cuò)誤嗎, 如果成功的話就是nil
public var error: Error? {
switch self {
case .Success:
return nil
case .Failure(let error):
return error
}
}
}
真的 大神就是大神,我可是寫(xiě)不出這么的結(jié)構(gòu)體寫(xiě)法, 還是要多多學(xué)習(xí),
對(duì)于結(jié)果體 我的理解就是,Swift已經(jīng)很強(qiáng)大了, 結(jié)果體完全可以取代對(duì)象的建立, 就是創(chuàng)建屬性,分配內(nèi)存什么的, 而且Swift 居然可以封裝初始化話代碼了
這里貼一段我的數(shù)據(jù)處理示例代碼
func getAllDepartmentRequest(deptName deptName: String?, finish:(dict: [String: AnyObject]?, error: NSError?) -> ()){
let path = "mGetAllDeptB.htm"
let parameter = ["deptName" : ""]
request(.POST, baseURL + path, parameters: parameter).responseJSON { (response) -> Void in
// 利用 result中的isSuccess 確定是否請(qǐng)求成功
if response.result.isSuccess{
SVProgressHUD.dismiss()
LXLLOG(response)
// 利用 result中的 value 來(lái)獲取響應(yīng)結(jié)果數(shù)據(jù)
let date = response.result.value as! [String : AnyObject]
let source = date["callBackData"]
LXLLOG(source)
// 將數(shù)據(jù)傳入 閉包, 進(jìn)行外界回調(diào), 這里就要活用閉包, 進(jìn)行數(shù)據(jù)回調(diào),監(jiān)聽(tīng)
finish(dict: response.result.value as? [String : AnyObject], error: nil)
}else
{
SVProgressHUD.showErrorWithStatus("數(shù)據(jù)獲取失敗,請(qǐng)檢查網(wǎng)絡(luò)")
finish(dict: nil, error: response.result.error)
}
}
}