OfflineRequestManager是一个Swift框架,用于确保在设备离线或应用终止时发送网络请求。
使用方法
OfflineRequestManager通过将网络请求封装在OfflineRequest对象中,并使用Alamofire观察当前网络可达性来实现。如果应用已经在线,则请求将立即执行。最简单的实现可能是这样的:
import OfflineRequestManager
class SimpleRequest: OfflineRequest {
func perform(completion: @escaping (Error?) -> Void) {
doMyNetworkRequest(withCompletion: { response, error in
handleResponse(response)
completion(error)
})
}
}
然后是:
OfflineRequestManager.defaultManager(queueRequest: SimpleRequest())
就这样!如果将网络相关的错误传递到完成块,OfflineRequestManager将保留请求并在稍后重试。其他错误将默认从队列中删除,但如果需要,有可选的代理方法允许进行调整和重新提交。
实际上,请求可能关联着一些数据。您还可能想要确保即使在应用退出或(天哪!)崩溃的情况下,也要发送请求。对于这些场景,代码将类似于:
class MoreRealisticRequest: OfflineRequest {
//arbitrary sample properties to demonstrate data persistence; could be replaced with anything
let stringProperty: String
let intProperty: Int
init(string: String, int: Int) {
self.stringProperty = string
self.intProperty = int
}
//instantiates the OfflineRequest from the saved dictionary
required init?(dictionary: [String: Any]) {
guard let stringProperty = dictionary["property1"] as? String, let intProperty = dictionary["property2"] as? Int else { return nil }
self.init(string: stringProperty, int: intProperty)
}
//provides OfflineRequestManager with a dictionary to save in the Documents directory
var dictionaryRepresentation: [String : Any]? {
return ["property1": stringProperty, "property2": intProperty]
}
func perform(completion: @escaping (Error?) -> Void) {
doMyNetworkRequest(withString: stringProperty, int: intProperty, andCompletion: { response, error in
handleResponse(response)
completion(error)
})
}
}
使用NSKeyedArchiver将dictionaryRepresentation提供的数据写入磁盘以保留,直到请求完成(注意:默认情况下,Foundation对象会保存,但在此字典中的自定义对象必须遵守NSCoding才能存档)。在这种情况下,需要有一个代理,让OfflineRequestManager在应用重新启动时知道如何处理存档的字典。
class ClassThatHandlesNetworkRequests: OfflineRequestManagerDelegate {
init() {
//whatever other stuff is going on
OfflineRequestManager.defaultManager.delegate = self
}
func offlineRequest(withDictionary dictionary: [String : Any]) -> OfflineRequest? {
return MoreRealisticRequest(dictionary: dictionary)
}
}
最后:
OfflineRequestManager.defaultManager(queueRequest: MoreRealisticRequest(requestData: relevantData))
就这么简单™。其他类型的请求可以由同一个代理处理,或者使用manager(withFileName:)而不是defaultManager将其排队,从而使用完全不同的OfflineRequestManager实例。还有几个基于请求进度更新并允许更精细错误处理的可选代理方法。默认情况下,管理器将一次发送最多10个排队请求,给它们120秒以完成;这两个数字都是可配置的(例如,限制为1个并发请求,以确保它们按顺序发送)。
文档
有关详细文档,请参阅OfflineRequestManager.swift文件中列出的接口的注释。
示例
要获取更详细的示例用法,请参考示例项目,该项目包含了一个图像上传请求的简单演示和一个测试套件,用于验证所有可用接口。
许可
OfflineRequestManager遵循MIT许可证。详细信息请参阅LICENSE文件。