Creating a custom plugin(创建自定义的插件)--Moya文档

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<Response, MoyaError>, 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<Response, MoyaError>, 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:请注意,这个例子通常会失败,因为在同一视图控制器中呈现一个警告两次是不允许的

总结 这小节的核心:

  1. 如何自定义插件,对请求过程进行友好提示
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,172评论 25 709
  • 获取分组中某一个子分组 re['(\d+)/']返回匹配的数字re['(\d+)(/)'][1]返回匹配的/ 2....
    PeterWang2017阅读 845评论 0 0
  • 传世大作《对弈江山》制片人工作日志六 剧组还有很多很多有特色的管理者,因为本人精力有限,就在这儿整体简单说说,其中...
    AA牧之源山庄阅读 2,732评论 2 0
  • 平时皮肤都不错 只是要见喜欢的人之前 偶尔会有问题 忽然 嘴唇起水泡 脸上起痘 你看 见你的心情都快要跟 见恋人差...
    不正常生物研究中心阅读 1,488评论 0 14
  • 天才也必須要以世人能理解的方式展現其才華,才能在他生前享有天才的榮耀,否則就只能是一個孤獨的先行者,鬱鬱而終,甚至...
    rhinodale阅读 1,488评论 0 1