68
GitHub - MQZHot/DaisyNet: 1. - Alamofire与Cache封装 , 更容易存储请求数据. 2. -...
source link: https://github.com/MQZHot/DaisyNet
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
README.md
DaisyNet
对Alamofire与Cache的封装实现对网络数据的缓存,可以存储JSON,String,Data,接口简单明了.
使用
1. 网络请求
注意: 如果你的参数中带有时间戳、token等变化的参数,这些参数需要写在dynamicParams
参数中,避免无法读取缓存
func request( _ url: String, method: HTTPMethod = .get, params: Parameters? = nil, dynamicParams: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil) -> RequestTaskManager
- 缓存数据只需要调用
.cache(true)
,不调用或者.cache(false)
则不缓存 - 调用
responseCacheAndString
可以先读取缓存数据,再读取网络数据 - 通过
isCacheData
属性可以区分缓存数据还是网络数据
DaisyNet.request(url, params: params).cache(true).responseCacheAndJson { value in switch value.result { case .success(let json): if value.isCacheData { print("我是缓存的") } else { print("我是网络的") } case .failure(let error): print(error) } }
- 你也可以分别读取缓存数据和网络数据,如下代码
- 调用
cacheJson
方法获取缓存数据,调用responseJson
获取网络数据
DaisyNet.request(url, params: params).cache(true).cacheJson { json in print("我是缓存的") }.responseJson { response in print("我是网络的") }
- 如果你不需要缓存,可以直接调用
responseJson
方法
DaisyNet.request(url).responseString { response in switch response { case .success(let value): print(value) case .failure(let error): print(error) } }
- 同理,如果你要缓存
Data
或者String
,与JSON
是相似的
/// 先读取缓存,再读取网络数据 DaisyNet.request(url).cache(true).responseCacheAndString { value in } DaisyNet.request(url).cache(true).responseCacheAndData { value in }
/// 分别获取缓存和网络数据 DaisyNet.request(url).cache(true).cacheString { string in print("我是缓存的") }.responseString { response in print("我是网络的") }
- 取消请求
DaisyNet.cancel(url, params: params)
- 清除缓存
/// 清除所有缓存 func removeAllCache(completion: @escaping (Bool)->()) /// 根据url和params清除缓存 func removeObjectCache(_ url: String, params: [String: Any]? = nil, completion: @escaping (Bool)->())
2. 下载
DaisyNet.download(url).downloadProgress { progress in /// 下载进度 }.response { response in /// 下载完成 }
- 如果正在下载中退出当前界面,再次进入时可以通过以下方法获取下载进度,并改变UI
DaisyNet.downloadProgress(url) { print($0) }?.response(completion: { _ in print("下载完成") })
- 获取下载状态
DaisyNet.downloadStatus(url)
- 获取下载百分比
DaisyNet.downloadPercent(url)
- 获取下载完成后文件所在位置
DDaisyNet.downloadFilePath(url)
- 删除某个下载
DaisyNet.downloadDelete(url)
- 取消某个下载
DaisyNet.downloadCancel(url)
- 取消所有下载
DaisyNet.downloadCancelAll()
Install
1.pod 'DaisyNet'
2.pod install / pod update
Author
- Email: [email protected]
LICENSE
DaisyNet is released under the MIT license. See LICENSE for details.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK