WBAlamofire
是什么
WBAlamofire 是基于 Alamofire 的高层次请求工具。它提供了一个高层级的 API 用于网络请求。
WBAlamofire 是从 YTKNetwork 的 Swift 版本。
功能
- 可以通过过期时间缓存响应
- 可以按照版本号缓存响应
- 设置公共基础 URL 和 CDN URL
- 验证 JSON 响应
- 恢复下载
- 响应和下载的缓存管理器
闭包
和代理
回调- 批量请求(查看
WBAlBatchRequest
) - 链式请求(查看
WBAlChainRequest
) - URL 过滤器,替换部分 URL 或附加公共参数
- 插件机制,处理请求的开始和结束。提供了一个显示“加载”HUD的插件。
安装
WBAlamofire支持多种方法在项目中安装库。
CocoaPods
CocoaPods 是Objective-C的依赖管理器,它自动化并简化了使用第三方库(如WBAlamofire)在项目中操作的过程。您可以使用以下命令安装它
$ gem install cocoapods
需要CocoaPods 1.2.0+来编译WBAlamofire。
Podfile
要使用CocoaPods将WBAlamofire集成到您的Xcode项目中,请将其指定在您的 Podfile
中
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
target 'TargetName' do
use_frameworks!
pod 'WBAlamofire'
end
使用在cocoapods中使用的swift 4.0/4.2
pod 'WBAlamofire', '1.2.1'
然后,运行以下命令
$ pod install
Carthage
Carthage 是一个集中的依赖管理器,它构建您的依赖并为您提供二进制框架。
您可以使用以下命令使用 Homebrew 安装Carthage
$ brew update
$ brew install carthage
要使用Carthage将WBAlamofire集成到您的Xcode项目中,请将其指定在您的 Cartfile
中
github "JsonBin/WBAlamofire"
运行 carthage
以构建框架,并将构建的 WBAlamofire.framework
拖至您的Xcode项目中。
Swift Package Manager
Swift Package Manager 是一个用于自动化Swift代码分配的工具,集成到swift编译器中。它处于初级开发阶段,但WBAlamofire不支持在支持的平台上使用。
一旦您设置了Swift包装,将WBAlamofire作为依赖项添加到 Package.swift
的 dependencies
值中就像添加它一样简单。
dependencies: [
.package(url: "https://github.com/JsonBin/WBAlamofire.git", from: "2.0.0")
]
需求
- iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
- Xcode 10.2+
- Swift 5.0+
WBAlamofire 版本 | Alamofire 版本 | 最低 iOS 目标 | 最低 macOS 目标 | 最低 watchOS 目标 | 最低 tvOS 目标 | 备注 |
---|---|---|---|---|---|---|
1.x | 4.x | iOS 8 | OS X 10.10 | watchOS 2.0 | tvOS 9.0 | 需要 Xcode 9+。 |
2.x | 5.x | iOS 10 | OS X 10.12 | watchOS 3.0 | tvOS 10.0 | 需要 Xcode 10.2+。 |
WBAlamofire 基于 Alamofire。关于版本兼容性的更多细节可以在 Alamofire README 中找到。
演示
WBAlConfig 类
我们应该在应用程序启动之初设置 WBAlConfig 的属性,示例如下
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
WBAlConfig.shared.baseURL = "https://timgsa.baidu.com/"
WBAlConfig.shared.debugLogEnable = true
return true
}
我们可以在应用程序启动之初设置 LoadView 属性
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
WBAlConfig.shared.loadViewText = "Login"
WBAlConfig.shared.loadViewTextColor = .red
WBAlConfig.shared.loadViewAnimationType = .system
return true
}
WBAlRequest 类
class RegisterApi: WBAlRequest {
private let phone: String
private let psd: String
init(phone: String, psd: String) {
self.phone = phone
self.psd = psd
}
/// request url
override var requestURL: String {
return "/adf/2"
}
/// request params
override var requestParams: [String : Any]? {
return ["phone": phone, "password": psd]
}
/// request method
override var requestMethod: WBAlHTTPMethod {
return .post
}
/// request params encoding
override var paramEncoding: WBAlParameterEncoding {
return .json(encode: .default)
}
override func requestCompleteFilter() {
super.requestCompleteFilter()
// request success, you can dely response in there.
}
override func requestFailedFilter() {
super.requestFailedFilter()
// request failed. you can do something in there.
}
}
之后,您可以调用请求。我们可以使用 start()
或 start(_:,failure:)
方法在网络请求队列中发送请求。
let res = RegisterApi(phone: "177xxxx2467", psd: "123456")
res.ignoreCache = true // whether don't use cache data. Default is false.
res.start({ (quest) in
// you can use self here, retain cycle won't happen
print("Success!")
//..
}) { (quest) in
// you can use self here, retain cycle won't happen
print("Failed!")
//..
}
WBActivityIndicatorView 类
WBAlamofire 提供了一套仅支持 iOS 系统使用的插件。在网络请求显示默认的“加载”风格 HUD 时候,插件会被使用。该插件有两种动画效果,一种为系统动画,另一种为自定义动画。该插件默认处于禁用状态,若要使用插件,可以参考以下示例代码。
为每个请求分别设置。
class login : WBAlRequest {
/// open the HUD plug-in
override var showLoadView: Bool {
return true
}
/// set HUD text
override var showLoadText: String? {
return "Login"
}
/// set the HUD font
override var showLoadTextFont: UIFont? {
return .systemFont(ofSize: 19)
}
/// set the HUD textcolor
override var showLoadTextColor: UIColor? {
return .red
}
/// set the HUD animation effects
override var showLoadAnimationType: AnimationType? {
// .system use system animation
// .native use a custom animation
return .native
}
/// set the HUD font display position
override var showLoadTextPosition: TextLabelPosition? {
// .no don't show the words
// .bottom on the bottom of the animation
return .no
}
}
在应用启动时统一设置。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
WBAlConfig.shared.loadViewText = "Login"
WBAlConfig.shared.loadViewTextFont = .systemFont(ofSize: 16)
WBAlConfig.shared.loadViewTextColor = .red
WBAlConfig.shared.loadViewAnimationType = .system
WBAlConfig.shared.loadViewTextPosition = .bottom
}
进行统一设置时,然而需要为每个请求分别设置设置,使 HUD 插件处于可用状态。
class login : WBAlRequest {
/// open the HUD plug-in
override var showLoadView: Bool {
return true
}
}
WBAlCache 类
WBAlamofire 提供了一种缓存处理机制。它包含请求结果的集合和 APIS 下载数据的处理,包括统计、删除等功能。
// all the download cache file size
WBAlCache.shared.downloadCacheSize
// all requests the cache file size
WBAlCache.shared.responseCacheFilesSize
// remove single download file
WBAlCache.shared.removeDownloadFiles(with: `YourFileName`)
// remove all requests results cache file
WBAlCache.shared.removeCacheFiles()
// remove all the downloaded file
WBAlCache.shared.removeDownloadFiles()
// remove all download cache and network request results
WBAlCache.shared.removeAllFiles()
可续传下载
若要启用可续传下载,您只需重写 resumableDownloadPath
方法,并提供一个要保存下载文件的路径。文件将自动保存在该路径。
我们可以修改上述示例以支持可续传下载。
class down: WBAlRequest {
override var requestURL: String {
return "timg?image&quality=80&size=b9999_10000&sec=1490781577869&di=e130b6d26a45afb47f42cb3c14edc2f6&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F5%2F553dc1e2be070.jpg"
}
override var resumableDownloadPath: String {
return "picture.png"
}
override var responseType: WBAlResponseType {
return .data
}
}
上传
您可以使用 4-5 行代码轻松将数据上传到服务器
class upload: WBAlRequest {
private let data: Data?
init(data: Data?) {
self.data = data
}
override var requestURL: String {
return "v2/upload/album"
}
override var requestMethod: WBAlHTTPMethod {
return .post
}
// TODO: Upload data to server, implement any of the following three methods
override var requestDataClosure: WBAlRequest.WBAlMutableDataClosure? {
if let data = self.data {
return { mutlidata in
mutlidata.append(data, withName: "file", mimeType: "image/jpg")
}
}
return nil
}
override var uploadData: Data? {
return data
}
override var uploadFile: URL? {
return URL(fileURLWithPath: "xxxx")
}
}
您只需实现 requestDataClosure
/uploadData
/uploadFile
中的任意一个方法来上传文件。
缓存响应数据
我们已经实现了 login
,用于获取用户信息。
我们可能希望缓存响应。在以下示例中,我们重写了 cacheInSeconds
方法,然后我们的 API 将会自动缓存指定时间内数据。如果缓存数据未过期,API 的 start()
和 start(_:,failure:)
将直接返回缓存数据作为结果。
class login : WBAlRequest {
override var baseURL: String {
return "http://www.baidu.com/"
}
override var requestURL: String {
return "userLogin"
}
override var requestMethod: WBAlHTTPMethod {
return .post
}
override var paramEncoding: WBAlParameterEncoding {
return .json(encode: .default)
}
override var requestParams: [String : Any]? {
return ["username":"151xxxx7833", "password":"123456"]
}
override func requestCompletePreprocessor() {
super.requestCompletePreprocessor()
WBAlog("request done!")
}
/// the request of validity cache Settings for 10 minutes
override var cacheInSeconds: TimeInterval {
return 10 * 60
}
override var showLoadView: Bool {
return true
}
override var showLoadText: String? {
return "Login"
}
}
缓存机制对控制器是透明的,这意味着请求调用者只需在不造成任何实际网络流量的情况下,调用请求后即可立即获得结果,只要其缓存的数据保持有效。
感谢
感谢YTKNetwork和Alamofire的贡献者。
有关更多信息,请参阅YTKNetwork。
许可证
WBAlamofire采用MIT许可证。有关更多信息,请参阅LICENSE文件。