看看最后的代碼
import UIKit
import AFNetworking
import MBProgressHUD
import Toast
extension NSObject {
func GET(URLString:String, parameters:[String:AnyObject]?, showHUD:Bool = true, success:((AnyObject?) -> Void)?, failure:((NSError) -> Void)? ){
let manager = AFHTTPSessionManager()
manager.requestSerializer.timeoutInterval = 10
let keyWindow = UIApplication.sharedApplication().delegate!.window!
if showHUD {
MBProgressHUD.showHUDAddedTo(keyWindow, animated: true)
}
manager.GET(URLString, parameters: parameters, success: { (operation, responseObject) -> Void in
if showHUD {
MBProgressHUD.hideAllHUDsForView(keyWindow, animated: true)
}
success?(responseObject)
}, failure: { (aFHTTPRequestOperation, error) -> Void in
if showHUD {
MBProgressHUD.hideAllHUDsForView(keyWindow, animated: true)
keyWindow?.makeDefaultToast("網(wǎng)絡異常,請檢查網(wǎng)絡")
}
failure?(error)
})
}
func POST(URLString:String, parameters:[String:AnyObject]?, showHUD:Bool = true, success:((AnyObject?) -> Void)?, failure:((NSError) -> Void)?){
let manager = AFHTTPSessionManager()
manager.requestSerializer.timeoutInterval = 10
let keyWindow = UIApplication.sharedApplication().keyWindow
if showHUD {
MBProgressHUD.showHUDAddedTo(keyWindow, animated: true)
}
manager.POST(URLString, parameters: parameters, success: { (operation, responseObject) -> Void in
if showHUD {
MBProgressHUD.hideAllHUDsForView(keyWindow, animated: true)
}
success?(responseObject)
}, failure: { (aFHTTPRequestOperation, error) -> Void in
if showHUD {
MBProgressHUD.hideAllHUDsForView(keyWindow, animated: true)
keyWindow?.makeDefaultToast("網(wǎng)絡異常,請檢查網(wǎng)絡")
}
failure?(error)
})
}
}
extension UIView {
func makeDefaultToast(message:String) {
makeToast(message, duration: 2, position: CSToastPositionCenter)
}
}
import
在Cocospods中加入use_frameworks!配置后,就可以類似import UIKit一樣,import相應的pod libraries,不需要在bridge文件中導入相應的頭文件了.
extension NSObject
因為目的是所有的類都可以使用它進行網(wǎng)絡請求,所以選擇擴展NSObject
方法的參數(shù)
- URLString: 請求的URL地址字符串
- parameters: 參數(shù)Dictionary,可選類型說明可以傳遞nil;Dictionary的key是字符串類型,value是AnyObject,表示可以傳遞任何Swift基本數(shù)據(jù)類型.
- showHUD: 不傳遞這個參數(shù),它的默認值會是true,表示請求時候會彈出MBProgressHUD蒙層,禁止用戶進行別的操作,false表示是在后臺默默的進行網(wǎng)絡請求,用戶察覺不到.
- success: 可選類型, 請求成功的回調(diào)閉包,閉包的參數(shù)是AnyObject?,表示請求成功返回的數(shù)據(jù)
- failure: 可選類型, 請求失敗的回調(diào)閉包,閉包的參數(shù)是NSError, 需要函數(shù)調(diào)用者自己處理異常.
請求步驟
- AFHttpSessionManager是AFNetworking 3.0之后推薦的http請求方式了,初始化它的對象,設置網(wǎng)絡超時時間.
- 添加蒙層:將MBProgressHUD添加到Application的keyWindow上
- 調(diào)用AFHttpSessionManager對象的GET或者POST方法
- 請求成功:隱藏蒙層然后調(diào)用success閉包,方法名稱后面加?表示如果success閉包為nil,就不執(zhí)行任何操作,否則會崩潰.
- 請求失敗:隱藏蒙層然后調(diào)用failure閉包.
Toast
github地址 : https://github.com/scalessec/Toast
類似Android系統(tǒng)的Toast效果,它沒有焦點,不會阻塞交互,過一定的時間自動消失拒秘。主要用于向用戶顯示提示消息