一.前言
對于iOS開發(fā)者,應(yīng)該沒有不知道AFNetworking
的!它是一個用OC語言寫的網(wǎng)絡(luò)庫,對于AFNetworking
有很多著名的二次封裝,比如猿題庫團(tuán)隊(duì)的開源庫YTKNetwork
,它將AFNetworking
封裝成抽象父類,然后根據(jù)每個不同的網(wǎng)絡(luò)請求,都編寫不同的子類,子類繼承父類,來實(shí)現(xiàn)請求業(yè)務(wù)(OOP思想設(shè)計(jì))。
對于Swift開發(fā),優(yōu)雅的網(wǎng)絡(luò)開發(fā)框架Alamofire
當(dāng)是不二選擇,Alamofire
是建立在NSURLSession
上的封裝,可以直接使用Alamofire
進(jìn)行網(wǎng)絡(luò)請求,但是我們項(xiàng)目中往往需要一些“項(xiàng)目化”設(shè)置,所以習(xí)慣二次封裝。在Swift開源社區(qū),對Alamofire
二次封裝最有名的當(dāng)屬Moya
,它在底層將Alamofire
進(jìn)行封裝,對外提供更簡潔的接口供開發(fā)者調(diào)用(POP思想設(shè)計(jì)).
Alamofire
地址: https://github.com/Alamofire/Alamofire
Moya
地址: https://github.com/Moya/Moya
不過似乎在大型項(xiàng)目,比如使用Moya+RxSwift+MVVM
才能發(fā)揮Moya
的威力,所以對中小項(xiàng)目,大都會自己簡單對Alamofire
封裝下使用,網(wǎng)上搜索一下,封裝之后的使用方法幾乎都是下面這種方式:
NetworkTools.request(url: "api", parameters:p, success: { (response) in
// TODO...
}) { (error) in
// TODO...
}
這種應(yīng)該是受OC的影響,方法里面跟著2個Block
回調(diào)的思路。但在Swift里面就是兩個逃逸尾隨閉包@escaping closure
,雖然語法沒問題,但是我感覺怪怪的,特別是閉包里面代碼一多起來,{()}{()}
大括號看的暈暈的。
我受PromiseKit
和JQuery
啟發(fā),進(jìn)行了點(diǎn)
語法封裝,使用方法如下:
PromiseKit
是iOS/MacOS
中一個用來處理異步編程的框架。可以直接配合Alamofire
或者AFNetworking
進(jìn)行處理,功能很強(qiáng)大!
GitHub: https://github.com/mxcl/PromiseKit
二.使用方法A
// 進(jìn)行一個請求,不管失敗情況
HN.POST(url: url, parameters: p, datas: datas).success { (response) in
debugPrint("success: \(response)")
}
// 進(jìn)行一個請求,處理成功和失敗
HN.GET(url: url, parameters: p).success { (response) in
debugPrint("success: \(response)")
}.failed { (error) in
debugPrint("failed: \(error)")
}
// 上傳圖片
HN.POST(url: url, parameters: p, datas: datas).progress { (progress) in
debugPrint("progress: \(progress.fractionCompleted)")
}.success { (response) in
debugPrint("success: \(response)")
}.failed { (error) in
debugPrint("failed: \(error)")
}
正如上面代碼所示,成功和失敗都是使用點(diǎn)
語法進(jìn)行回調(diào),清晰明了,甚至你可以不管成功和失敗,只發(fā)送一個請求:
HN.GET(url: "api")
三.使用方法B
3.1 結(jié)合HWAPIProtocol
使用,這里新建一個struct
去實(shí)現(xiàn)HWAPIProtocol
:
struct APIItem: HWAPIProtocol {
var url: String { API.DOMAIN + URLPath } // 域名 + path
let description: String
let extra: String?
var method: HWHTTPMethod
private let URLPath: String // URL的path
init(_ path: String, d: String, e: String? = nil, m: HWHTTPMethod = .get) {
URLPath = path
description = d
extra = e
method = m
}
}
3.2. 項(xiàng)目里面,寫API的文件就可以設(shè)計(jì)為(模塊化):
struct API {
static var DOMAIN = "https://www.baidu.com/"
// MARK: Home模塊
struct Home {
static let homeIndex = APIItem("homeIndex", d: "首頁數(shù)據(jù)")
static let storeList = APIItem("homeIndex", d: "首頁門店列表", m: .post)
}
// MARK: 圈子模塊
struct Social {
static let socialIndex = APIItem("socialList", d: "圈子首頁列表")
}
}
3.3 網(wǎng)絡(luò)請求方式:
// 1.不帶參數(shù)
HN.fetch(API.Home.homeIndex).success { response in
print(response)
}
// 2.加上參數(shù)
let p: [String: Any] = ["name": "ZhangSan", "age": 22]
HN.fetch(API.Home.homeIndex, parameters: p).success { response in
print(response)
}
// 3.加上Header 和失敗情況
let h = ["Referrer Policy": "no-referrer-when-downgrade"]
HN.fetch(API.Home.homeIndex, headers: h).success { response in
print(response)
}.failed { error in
print(error)
}
可能有人疑問,為什么接口要加一個
description
,這里解釋一下:
1.在API文件里,能直接明白這接口是做什么的
2.在我項(xiàng)目里,有一個debug隱藏模塊,可以看到所有的API請求情況,可以看到這個description
3.在debug模塊里,不僅后臺Java同事能通過description
定位接口,測試同事也方便找接口
四.使用方法C
由于已經(jīng)為HWAPIProtocol
擴(kuò)展了已實(shí)現(xiàn)fetch()
方法,所以上面的請求可以簡化為更高階的方式:
// 1.不帶參數(shù)
API.Me.meIndex.fetch().success { response in
print("response -->", response)
}.failed { error in
print("error -->", error)
}
API.Home.homeIndex.fetch(success: {response in
print(response)
}, failed: {error in
print(error)
})
// 2.加上參數(shù)
let p: [String: Any] = ["name": "ZhangSan", "age": 22]
API.Home.homeIndex.fetch(p, success: { response in
print(response)
}) { error in
print(error)
}
// 3.加上Header 和失敗情況
let h = ["Referrer Policy": "no-referrer-when-downgrade"]
API.Home.homeIndex.fetch(p, headers: h, success: { response in
print(response)
}) { error in
print(error)
}
五.OC使用方法
OC的請求如下,具體可以看Demo,這里簡單列舉一個實(shí)例:
NSString *url = @"http://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js";
NSDictionary *dict = @{@"v": @(33)};
[HWNetworkingOC GET:url info:@"LOL英雄列表" parameters:dict success:^(id response) {
NSLog(@"%@", response);
} failed:^(NSString *error) {
NSLog(@"%@", error);
}];
六.思路?
設(shè)計(jì)思路其實(shí)很簡單,首先是一個單例,用于持有Alamofire.Session
和每個請求對象,順便定義幾個回調(diào)
/// Closure type executed when the request is successful
public typealias HNSuccessClosure = (_ JSON: Any) -> Void
/// Closure type executed when the request is failed
public typealias HNFailedClosure = (_ error: Any) -> Void
/// Closure type executed when monitoring the upload or download progress of a request.
public typealias HNProgressHandler = (Progress) -> Void
public class HWNetworking {
/// For singleton pattern
public static let shared = HWNetworking()
/// TaskQueue Array for (`Alamofire.Request` & callback)
private var taskQueue = [HWNetworkRequest]()
/// `Session` creates and manages Alamofire's `Request` types during their lifetimes.
var sessionManager: Alamofire.Session!
}
把每個請求封裝成對象,調(diào)用對象的success(...)
方法和failed(...)
等,獲得這個請求的成功和失敗回調(diào),回調(diào)之后,銷毀對象即可.
public class HWNetworkRequest: Equatable {
/// Alamofire.DataRequest
var request: DataRequest?
/// request response callback
private var successHandler: HNSuccessClosure?
/// request failed callback
private var failedHandler: HNFailedClosure?
/// `ProgressHandler` provided for upload/download progress callbacks.
private var progressHandler: HNProgressHandler?
// MARK: - Handler
/// Handle request response
func handleResponse(response: AFDataResponse<Any>) {
switch response.result {
case .failure(let error):
if let closure = failedHandler {
closure(error.localizedDescription)
}
case .success(let JSON):
if let closure = successHandler {
closure(JSON)
}
}
clearReference()
}
/// Processing request progress (Only when uploading files)
func handleProgress(progress: Foundation.Progress) {
if let closure = progressHandler {
closure(progress)
}
}
// MARK: - Callback
/// Adds a handler to be called once the request has finished.
public func success(_ closure: @escaping HNSuccessClosure) -> Self {
successHandler = closure
return self
}
/// Adds a handler to be called once the request has finished.
@discardableResult
public func failed(_ closure: @escaping HNFailedClosure) -> Self {
failedHandler = closure
return self
}
}
核心的請求方法如下:
extension HWNetworking {
public func request(url: String,
method: HTTPMethod = .get,
parameters: [String: Any]?,
headers: [String: String]? = nil,
encoding: ParameterEncoding = URLEncoding.default) -> HWNetworkRequest {
let task = HWNetworkRequest()
var h: HTTPHeaders? = nil
if let tempHeaders = headers {
h = HTTPHeaders(tempHeaders)
}
task.request = sessionManager.request(url,
method: method,
parameters: parameters,
encoding: encoding,
headers: h).validate().responseJSON { [weak self] response in
task.handleResponse(response: response)
if let index = self?.taskQueue.firstIndex(of: task) {
self?.taskQueue.remove(at: index)
}
}
taskQueue.append(task)
return task
}
}
再封裝幾個常用的POST和Get快捷方法:
/// Shortcut method for `HWNetworking`
extension HWNetworking {
@discardableResult
public func POST(url: String, parameters: [String: Any]? = nil, headers: [String: String]? = nil) -> HWNetworkRequest {
request(url: url, method: .post, parameters: parameters, headers: nil)
}
/// Creates a GET request
@discardableResult
public func GET(url: String, parameters: [String: Any]? = nil, headers: [String: String]? = nil) -> HWNetworkRequest {
request(url: url, method: .get, parameters: parameters, headers: nil)
}
}
大致的思路就如上面貼出的關(guān)鍵代碼,限于篇幅,這里不貼完整的代碼了,可以直接去Github上clone
下來看看,實(shí)現(xiàn)的大致功能如下:
- 常規(guī)的POST/GET
- 網(wǎng)絡(luò)狀態(tài)監(jiān)聽和通知
- 上傳圖片的封裝(單張或者多張)
- 下載文件(沒有做,我這項(xiàng)目里沒有這樣的需求,不過方法留著了,自行擴(kuò)展即可)
將來要做的功能:
- 支持
closure
和delegate
兩種模式的回調(diào)方式 - 支持網(wǎng)絡(luò)請求
URL
的filter
,可以統(tǒng)一為網(wǎng)絡(luò)請求加上一些參數(shù),或者攔截請求結(jié)果 - 統(tǒng)一的
Header
設(shè)置
也歡迎大家把好的想法留言或者git Issues
,因?yàn)槲視陧?xiàng)目里使用這個類,所以后面如果有新的想法和功能,我都會更新維護(hù)的。
Github地址,GitHub點(diǎn)我或者復(fù)制下面鏈接:
https://github.com/HouWan/HWNetworking
從github上clone下以后,cd到目錄
SwiftDemo
,執(zhí)行pod install
命令即可運(yùn)行Demo
關(guān)于尾隨閉包
,可能有同學(xué)說,那系統(tǒng)很多API這么使用的,比如:
UIView.animate(withDuration: 1, animations: {
// TODO...
}) { (finished) in
// TODO...
}
這個看大家習(xí)慣了,不過在最新的Swift 5.3
中,針對這塊多個尾隨閉包有了新的語法糖:
// old Swift3
UIView.animate(withDuration: 0.3, animations: {
self.view.alpha = 0
}, completion: { _ in
self.view.removeFromSuperview()
})
// still old Swift4/5
UIView.animate(withDuration: 0.3, animations: {
self.view.alpha = 0
}) { _ in
self.view.removeFromSuperview()
}
// new swift 5.3
UIView.animate(withDuration: 0.3) {
self.view.alpha = 0
} completion: { _ in
self.view.removeFromSuperview()
}
END。
我是小侯爺。
在帝都艱苦奮斗,白天是上班族,晚上是知識服務(wù)工作者。
如果讀完覺得有收獲的話,記得關(guān)注和點(diǎn)贊哦。
非要打賞的話,我也是不會拒絕的。