NetworkLayerSwift 0.4.0

NetworkLayerSwift 0.4.0

Hossam Sherif 维护。



 
依赖
Moya~> 14.0
ReachabilitySwift>= 0
DataCache>= 0
 

  • 作者:
  • hossamsherif

NetworkLayerSwift

CI Status Version License Platform

NetworkLayer 是一个基于 Moya 网络库和 ObjectMapper 构建的容器式网络层。

特性

  • 用于 API 请求:
    • 通过 sendRequest 发送纯请求,仅成功和失败
    • 通过 fetchData 获取数据请求,返回映射对象结果或错误
  • 配置键和 NotificationCenter 的可达性管理器 - 基于 ReachabilitySwift
  • 当网络连接不可达时发送通知,并附带上一次失败的 API 调用 - 用于处理重试和自动重新连接
  • 通过提供缓存响应键进行缓存响应 - 仅适用于 fetchData - 基于 DataCache
  • 通过将 true 传递给 shouldRetryOn401 参数来在 401 错误上重试 - 还需要将重新验证块传递给 NL.reauthenticateBlock
  • 上传和下载请求的进度块以获取当前进度
  • 使用可取消的请求包装器取消请求并检查请求状态

示例

要运行示例项目,请克隆仓库,然后首先从 Example 目录运行 pod install

安装

NetworkLayer 通过 CocoaPods 提供。要安装它,请在您的 Podfile 中添加以下行:

pod 'NetworkLayerSwift'

使用方法

普通API调用

enum ExampleTarget: TargetType {
    case getMessage
    case getPlain
    ...
}
...
 //Plain request without response
let getPlainRequest = NL.sendRequest(target: ExampleTarget.getPlain) { (result)
    switch result {
    case .success:
    ...
    case .failure(let error): 
    ...
    }
}
//To cancel request
getPlainRequest.cancel()

使用缓存获取数据(通过提供cachedResponseKey进行缓存)

NL.fetchData(target: ExampleTarget.getMessage,
             responseClass: NLBaseResponse<MessageModel>.self,
             cachedResponseKey: ExampleTarget.getMessage.path) { (result, cached) in
    switch result {
    case .success(let response):
    let messageModel = response?.data // of type MessageModel
    let isCached = cached // will be true when returned from local cache
    ...
    case .failure(let error):
    ...
    }
}

不使用缓存获取数据(跳过cachedResponseKey以禁用缓存)

NL.fetchData(target: ExampleTarget.getMessage,
             responseClass: NLBaseResponse<MessageModel>.self) { (result, _) in
    switch result {
    case .success(let response):
    let messageModel = response?.data 
    ...
    case .failure(let error):
    ...
    }
}

在401未授权错误时重试

NL.reauthenticateBlock = { retryBlock in
// call you authenticatation api
authenticate(user) { result in
    switch result {
    case .success:
    ...
    retryBlock()
    case. failure:
    ...
    //should skip calling retrtBlock
    }
}

在连接恢复时自动重新调用上次失败的API进行重试处理

NotificationCenter.default.addObserver(self, selector: #selector(apiDidFail(_:)), name: .NLApiConnectionFailure, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(connectionDidChange(_:)), name: .NLDidChangeConnection, object: nil)

var failedRequests = [(()->())]()

@objc func connectionDidChange(_ notification:Notification) {
    if let connectionState = notification.userInfo?[NL.reachabilityConfiguration.didChangeConnectionUserInfoKey] as? ConnectionType,
        [.wifi, .cellular].contains(connectionState)  { // connection restored
        let retryRequest = failedRequests.popLast()
        retryRequest?()
    }    
}

@objc func apiDidFail(_ notification:Notification) {
    if let failedRquest = notification.userInfo?[NL.configuration.apiConnectionFailureUserInfoKey] as? () -> () {
        self.failedRequests.append(failedRquest)
    }
}

注意:应在进行任何API调用之前设置。

作者

hossamsherif, [email protected]

许可协议

NetworkLayer遵守MIT许可协议。请查阅LICENSE文件以获取更多信息。