Swift5基于Alamofire5的封裝

一.前言

對于iOS開發者,應該沒有不知道AFNetworking的!它是一個用OC語言寫的網絡庫,對于AFNetworking有很多著名的二次封裝,比如猿題庫團隊的開源庫YTKNetwork,它將AFNetworking封裝成抽象父類,然后根據每個不同的網絡請求,都編寫不同的子類,子類繼承父類,來實現請求業務(OOP思想設計)。

對于Swift開發,優雅的網絡開發框架Alamofire當是不二選擇,Alamofire是建立在NSURLSession上的封裝,可以直接使用Alamofire進行網絡請求,但是我們項目中往往需要一些“項目化”設置,所以習慣二次封裝。在Swift開源社區,對Alamofire二次封裝最有名的當屬Moya,它在底層將Alamofire進行封裝,對外提供更簡潔的接口供開發者調用(POP思想設計).

Alamofire地址: https://github.com/Alamofire/Alamofire
Moya地址: https://github.com/Moya/Moya

不過似乎在大型項目,比如使用Moya+RxSwift+MVVM才能發揮Moya的威力,所以對中小項目,大都會自己簡單對Alamofire封裝下使用,網上搜索一下,封裝之后的使用方法幾乎都是下面這種方式:

NetworkTools.request(url: "api", parameters:p, success: { (response) in
    // TODO...
}) { (error) in
    // TODO...
}

這種應該是受OC的影響,方法里面跟著2個Block回調的思路。但在Swift里面就是兩個逃逸尾隨閉包@escaping closure,雖然語法沒問題,但是我感覺怪怪的,特別是閉包里面代碼一多起來,{()}{()}大括號看的暈暈的。

我受PromiseKitJQuery啟發,進行了語法封裝,使用方法如下:

PromiseKitiOS/MacOS中一個用來處理異步編程的框架。可以直接配合Alamofire或者AFNetworking進行處理,功能很強大!
GitHub: https://github.com/mxcl/PromiseKit

二.使用方法A

// 進行一個請求,不管失敗情況
HN.POST(url: url, parameters: p, datas: datas).success { (response) in
    debugPrint("success: \(response)")
}

// 進行一個請求,處理成功和失敗
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)")
}

正如上面代碼所示,成功和失敗都是使用語法進行回調,清晰明了,甚至你可以不管成功和失敗,只發送一個請求:

HN.GET(url: "api")

三.使用方法B

3.1 結合HWAPIProtocol使用,這里新建一個struct去實現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. 項目里面,寫API的文件就可以設計為(模塊化):

struct API {
    static var DOMAIN = "https://www.baidu.com/"

    // MARK: Home模塊
    struct Home {
        static let homeIndex = APIItem("homeIndex", d: "首頁數據")
        static let storeList = APIItem("homeIndex", d: "首頁門店列表", m: .post)
    }

    // MARK: 圈子模塊
    struct Social {
        static let socialIndex = APIItem("socialList", d: "圈子首頁列表")
    }
}

3.3 網絡請求方式:

// 1.不帶參數
HN.fetch(API.Home.homeIndex).success { response in
    print(response)
}

// 2.加上參數
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.在我項目里,有一個debug隱藏模塊,可以看到所有的API請求情況,可以看到這個description
3.在debug模塊里,不僅后臺Java同事能通過description定位接口,測試同事也方便找接口


四.使用方法C

由于已經為HWAPIProtocol擴展了已實現fetch()方法,所以上面的請求可以簡化為更高階的方式:

// 1.不帶參數
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.加上參數
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,這里簡單列舉一個實例:

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);
}];

六.思路?

設計思路其實很簡單,首先是一個單例,用于持有Alamofire.Session和每個請求對象,順便定義幾個回調

/// 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!
}

把每個請求封裝成對象,調用對象的success(...)方法和failed(...)等,獲得這個請求的成功和失敗回調,回調之后,銷毀對象即可.

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)
    }
}

大致的思路就如上面貼出的關鍵代碼,限于篇幅,這里不貼完整的代碼了,可以直接去Github上clone下來看看,實現的大致功能如下:

  • 常規的POST/GET
  • 網絡狀態監聽和通知
  • 上傳圖片的封裝(單張或者多張)
  • 下載文件(沒有做,我這項目里沒有這樣的需求,不過方法留著了,自行擴展即可)

將來要做的功能:

  • 支持closuredelegate兩種模式的回調方式
  • 支持網絡請求URLfilter,可以統一為網絡請求加上一些參數,或者攔截請求結果
  • 統一的Header設置

也歡迎大家把好的想法留言或者git Issues,因為我會在項目里使用這個類,所以后面如果有新的想法和功能,我都會更新維護的。

Github地址GitHub點我或者復制下面鏈接:
https://github.com/HouWan/HWNetworking

從github上clone下以后,cd到目錄SwiftDemo,執行pod install命令即可運行Demo


關于尾隨閉包,可能有同學說,那系統很多API這么使用的,比如:

UIView.animate(withDuration: 1, animations: {
    // TODO...
}) { (finished) in
    // TODO...
}

這個看大家習慣了,不過在最新的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。
我是小侯爺。
在帝都艱苦奮斗,白天是上班族,晚上是知識服務工作者。
如果讀完覺得有收獲的話,記得關注和點贊哦。
非要打賞的話,我也是不會拒絕的。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容