向用户iOS显示错误信息的最佳方法

时间:2016-03-03 14:13:35

标签: ios objective-c

对于资深和经验丰富的开发人员来说,这可能是一个显而易见的问题,所以我真的很害怕问它。

假设我有一个移动应用程序,它为不同的数据模型调用了太多的RESTful API。假设有ViewController A,B,C可以在这些模型上进行CRUD。现在有几件事可能会出错。每个呼叫都有一个故障块。我正在使用Strongloop / Loopback ios sdk。

默默忽略这样的错误的策略:

[repo logoutWithSuccess:^(){
    // ... success code
} failure:CALLBACK_FAILURE_BLOCK];

CALLBACK_FAILURE_BLOCK定义为

#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

#define CALLBACK_FAILURE_BLOCK \
    ^(NSError *error) { \
    ALog("Callback failed: %@", error.description); \
    }

在一个理想的世界中会很棒,每个客户端验证都能完美运行,而且可以把头放在沙子里。

目前,我已在每个ViewController中定义了一个辅助函数,当这些调用失败时,它会向用户显示警报。

[self.trip saveWithSuccess:^(){
    //... success code
} failure:^(NSError *error){
    [self displayErrorWithMessage:[error localizedDescription]
                         andTitle:NSLocalizedString(@"Service Error", @"Server Error")];
}];

- (void)displayErrorWithMessage:(NSString*)msg andTitle:(NSString*)title{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:title
                                                                   message:msg
                                                            preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                          }];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

我正在考虑将这个辅助函数重构为一个常见的位置,例如AppDelegate(可能在协议中)。

这是一个正确的策略,你还有其他最好的方法来更好地设计它吗?

1 个答案:

答案 0 :(得分:1)

最近我在我的应用程序中使用了这种方法,我希望它能很好地处理错误。

为此,我创建了UIViewController的ErrorViewController子类(在My Case中它是VCBaseViewController,它是所有其他视图控制器的父类,它是UIViewController的子类)。你可以使用storyboard或xib,它取决于你。我在我的应用程序中使用了故事板。

我的ErrorViewController.h

@interface ErrorViewController : VCBaseViewController

@property (nonatomic, strong) NSString *errorTitle;
@property (nonatomic, strong) NSString *errorDescription;

@property(nonatomic,assign) ErrorPageType errorPage;

@property (weak, nonatomic) IBOutlet UILabel *lblErrorText;
@property (weak, nonatomic) IBOutlet UITextView *textViewErrorString;
@property (weak, nonatomic) IBOutlet UIButton *btnAction;

@end

ErrorViewController.m

@interface ErrorViewController ()

@end

@implementation ErrorViewController

- (void)viewDidLoad {
[super viewDidLoad];
[self configureNavigationBarWithStyle:NavigationStyleBackButton];
[self setViewControllerTitle:@"Error View"];
}

 - (void)viewWillAppear:(BOOL)animated{
 [super viewWillAppear:YES];

 switch (self.errorPage)
 {
    case ErrorTypeNetworkError:
    {

    }
        break;

    case ErrorTypeTechnicalError:
    {
        self.lblErrorText.text = @"Technical Error";
        self.textViewErrorString.text = @"Due to some technical error\n page not exist";
    }
        break;

    default:
    {
        self.lblErrorText.text = self.errorTitle;
        self.textViewErrorString.text = self.errorDescription;
    }
        break;
    }
   }

 - (IBAction)btnErrorAction:(id)sender{
 [self errorPageAction];
 }

 - (void)backButtonPressed{
 [self errorPageAction];
 }

 - (void)errorPageAction
 {
 switch (self.errorPage) 
  {
    case ErrorTypeNetworkError:
    {

    }
     break;
    case ErrorTypeProductNotAvailable:
    {
        [self popToPreviousController];
    }break;
    default:
    {
        [self popToPreviousController];
    }break;
  }
 }

 - (void)popToPreviousController
 {
  NSArray* viewcontrollers = [self.navigationController viewControllers];
 if(viewcontrollers.count>2)
 {
    int index = (int)viewcontrollers.count - 3;
    [self.navigationController popToViewController:[viewcontrollers objectAtIndex:index] animated:YES];
 }else{
    [self.navigationController popToRootViewControllerAnimated:YES];
  }
 }

我的故事板设计看起来像这样,其中包含错误图像错误标签和textView和后退按钮,因为我使用导航控制器。 [![在此处输入图像说明] [1]] [1]

我的BaseViewController.h

typedef enum {
 ErrorTypeNetworkError = 0,
 ErrorTypeTechnicalError,
 ErrorTypeNone
} ErrorPageType;

- (void)pushErrorViewcontroller:(NSError*)error;
- (void)pushErrorViewcontroller:(NSString*)errorTitle andErrorPage:(ErrorPageType)errorType;
- (void)pushErrorViewcontroller:(NSString *)errorTitle errorDescription:(NSString *)errorDescription errorType:(ErrorPageType)errorType;

BaseViewController.m

- (void)pushErrorViewcontroller:(NSString*)errorTitle andErrorPage:(ErrorPageType)errorType{
[self pushErrorViewcontroller:nil errorDescription:nil errorType:errorType];
}

- (void)pushErrorViewcontroller:(NSError*)error{
[self pushErrorViewcontroller:nil errorDescription:[error localizedDescription] errorType:ErrorTypeNone];
}

- (void)pushErrorViewcontroller:(NSString *)errorTitle errorDescription:(NSString *)errorDescription errorType:(ErrorPageType)errorType{
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
ErrorViewController *errorViewController  = [storyBoard instantiateViewControllerWithIdentifier:NSStringFromClass([ErrorViewController class])];
errorViewController.errorPage = errorType;
errorViewController.errorDescription = errorDescription;
errorViewController.errorTitle = errorTitle;
[self.navigationController pushViewController:errorViewController animated:YES];
}

我在其他视图Controller中调用errorView Controller Methods。

- (void) ServiceCallForOrderHistoryWithCurrentPageMark: (NSString *)page
{
__block __weak VCMyOrderViewController* blockMyOrderListView = self;

[[ModelManager sharedInstance] getMyOrderDetail:[[Configuration sharedConfig] getLoggedInUserId] andPageNumber:page completionBlock:^(id result, NSError *error)
 {
     if (!error)
     {        

         blockMyOrderListView.objOrderHistoryBaseClass = (OrderHistoryBaseClass *)result;

         if (blockMyOrderListView.objOrderHistoryBaseClass.rESPONSE.totalOrderCount.intValue == 0)
         {
             [blockMyOrderListView.tblMyOrder setHidden:YES];
             [blockMyOrderListView.viewNoOrders setHidden:NO];
         }
         else
         {
             [blockMyOrderListView setDataSourceMyOrders:blockMyOrderListView.objOrderHistoryBaseClass.rESPONSE];
             [blockMyOrderListView.tblMyOrder reloadData];
         }
     }
     else
     {
         [blockMyOrderListView pushErrorViewcontroller:error];
     }
 }];
}