ios - 谁应该负责显示带有登录表单的模式对话框?

标签 ios objective-c uiviewcontroller storyboard appdelegate

在我的应用委托(delegate)中,我创建了一个数据模型和 inject it into a root view controller我从 Storyboard中得到 while requesting user's credentials if needed from the start .稍后,当访问某些数据模型方法时,我需要验证用户的密码并重试触发密码重新验证的请求。

最明显的是将此功能构建到可能需要请求此信息的每个 View Controller 中,但我想尽可能避免这种情况,因为它使 Controller 不那么通用,也使测试更难。在我看来, Controller 必须对他们所提供的模型的内部工作原理一无所知。

将此功能添加到模型对我来说也不合适:管理用户交互完全超出了 MVC 中模型的职责。

谁应该负责显示带有相应 View Controller 的模态对话框以让用户输入他的凭据?

最佳答案

这可以通过回调使用很少的代码行来完成。回调 API 将在模型层定义(因此它是可重用的),但用户交互是在 Controller 级别实现的(因为这是它所属的位置)。

我不完全确定您的架构究竟是什么样子,根据您的描述,我假设该应用程序意识到您没有仅在请求失败时进行身份验证(您可能想要存储您的 token 到期日期并利用它,如果可能的话)。

基本思路:

在您的模型中,您有一个回调 block 属性(例如,在客户端类或您使用的任何其他模式上)。

@property (nonatomic, copy) void (^onNonauthenticatedRequest)(NSURLRequest *failedRequest, NSError *error);

当您的请求由于用户未通过身份验证而失败时,您在模型层中执行此 block 。

在 Controller 级别,您有一个 Controller 提示用户输入凭据(并且具有类似的回调模式)。

client.onNonauthenticatedRequest = ^(NSURLRequest *failedRequest, NSError *error) {

    ABCredentialsViewController *credentialsViewController = [ABCredentialsViewController new];
    credentialsViewController.onAuthenticationSuccess = ^{
        // This gets called after the authentication request succeeded
        // You want to refire failedRequest here
        // Make sure you use a weak reference when using the object that owns onAuthenticationFailure
    };

    credentialsViewController.onAuthenticationFailure = ^(NSError *) {
        // You might want to do something if the user is not authenticated and failed to provide credentials
    }

    [[UIApplication sharedApplication].delegate.window.topViewController presentViewController:credentialsViewController animated:YES];
    // or you could just have a method on UIViewController/your subclass to present the credentials prompt instead
};

逻辑在正确的地方,如果你想在不同的情况下以不同的方式处理未经身份验证的请求,你可以。

关于ios - 谁应该负责显示带有登录表单的模式对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672341/

相关文章:

ios - 解码AudioStreamBasicDescription的mFormatFlags编号(ASBD.mFormatFlags)

iphone - 在构造函数中获取属性集

ios - 在 swift xcode 中通过 View 发送数据

3.5寸模拟器显示时iOS UITableView高度问题

iphone - 当我们执行 presentViewController 时,幕后会发生什么?

ios - UILabel首字母小写

ios - 如何从任何 View 导航到初始 View Controller

ios - iPad 不遵守 Interface Builder 的 AutoLayout 约束

ios - 将 View 拖到界面生成器中的场景停靠栏中

ios - `: class` 在协议(protocol)声明中究竟做了什么?