Creating a custom plugin(创建自定义的插件)
作为构建一个自定义插件的一个例子,假设我们想通知用户关于网络活动当请求被发送时,我们显示一个带关于请求的基本信息的alert提示框。并让用户知道响应失败的请求(在本例中我们还需要假设我们不介意使用多个alert提示框打扰用户)
首先,我们创建一个遵循了PluginType协议的类,接收一个view Controller(用来展示alert提示框):
final class RequestAlertPlugin: PluginType {
private let viewController: UIViewController
init(viewController: UIViewController) {
self.viewController = viewController
}
func willSend(request: RequestType, target: TargetType) {
}
func didReceive(result: Result, target: TargetType) {
}
}
然后我们需要添加一些功能当请求被发送的时候:
func willSend(request: RequestType, target: TargetType) {
//make sure we have a URL string to display
guard let requestURLString = request.request?.url?.absoluteString else { return }
//create alert view controller with a single action
let alertViewController = UIAlertController(title: "Sending Request", message: requestURLString, preferredStyle: .alert)
alertViewController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
//and present using the view controller we created at initialization
viewController.present(viewControllerToPresent: alertViewController, animated: true)
}
最后,让我们来实现didReceive方法,当结果是一个错误的时候来展示一个alert提示框:
func didReceive(result: Result, target: TargetType) {
//only continue if result is a failure
guard case Result.failure(_) = result else { return }
//create alert view controller with a single action and messing displaying status code
let alertViewController = UIAlertController(title: "Error", message: "Request failed with status code: \(error.response?.statusCode ?? 0)", preferredStyle: .alert)
alertViewController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
//and present using the view controller we created at initialization
viewController.present(viewControllerToPresent: alertViewController, animated: true)
}
就是这样,你现在已经非常了解(And that's it, you now have very well informed, if slightly annoyed users.)
ps:请注意,这个例子通常会失败,因为在同一视图控制器中呈现一个警告两次是不允许的
总结 这小节的核心:
- 如何自定义插件,对请求过程进行友好提示