2013-04-26 105 views
0

对于我的iPhone应用程序,我需要处理在服务器返回一个错误的情况下,有一对夫妇的错误我感兴趣的手柄,如没有找到和超时。显示刷新页面IOS-Xamarin

我与Xamarin和Windows Azure的移动业务发展。到目前为止,我知道如何捕获这些异常,但是,如果出现异常,我想显示一个包含刷新按钮的视图,用户可以按刷新按钮以刷新(转到服务器并查看是否存在新数据,删除刷新视图,并显示新信息)。

这是我如何捕获由服务器抛出的异常:

public async RefreshAsync(){   
     try 
     { 
      var results = await DailyWorkoutTable.ToListAsync(); 
      wod = results.FirstOrDefault(); 
      SetupUI(); 
     } 
     catch(Exception e) 
     { 
      var ex = e.GetBaseException() as MobileServiceInvalidOperationException; 
      if(ex.Response.StatusCode == 404) 
      { 
       //this is where I need to set up the refresh view and 
       //and add a UIButton to it 
       Console.WriteLine("Daily workout not found"); 
      } 
     } 
    } 

我不知道什么是完成这一任务的正确的方式做。如果我创建一个UIView并向它添加一个UIButton,再次调用RefreshAsync的事件,它将不起作用,并不是最优雅的方式。

是否有这另一种方法?请帮忙。

回答

1

这里是你可以作为一个起点,用一个例子:

/// <summary> 
/// A class for performing Tasks and prompting the user to retry on failure 
/// </summary> 
public class RetryDialog 
{ 
    /// <summary> 
    /// Performs a task, then prompts the user to retry if it fails 
    /// </summary> 
    public void Perform(Func<Task> func) 
    { 
     func().ContinueWith(t => 
     { 
      if (t.IsFaulted) 
      { 
       //TODO: you might want to log the error 

       ShowPopup().ContinueWith(task => 
       { 
        if (task.IsCompleted) 
         Perform(func); 

       }, TaskScheduler.FromCurrentSynchronizationContext()); 
      } 

     }, TaskScheduler.FromCurrentSynchronizationContext()); 
    } 

    /// <summary> 
    /// Wraps a retry/cancel popup in a Task 
    /// </summary> 
    private Task ShowPopup() 
    { 
     var taskCompletionSource = new TaskCompletionSource<bool>(); 

     var alertView = new UIAlertView("", "Something went wrong, retry?", null, "Ok", "Cancel"); 
     alertView.Dismissed += (sender, e) => { 
      if (e.ButtonIndex == 0) 
       taskCompletionSource.SetResult(true); 
      else 
       taskCompletionSource.SetCanceled(); 
     }; 
     alertView.Show(); 

     return taskCompletionSource.Task; 
    } 
} 

要使用它:

var retryDialog = new RetryDialog(); 
retryDialog.Perform(() => DoSomethingThatReturnsTask()); 

这个例子之前异步/ AWAIT的支持,但如果你能重构它期望。

你也可以考虑把执行()返回任务,并成为异步 - 这取决于你的使用情况。