xamarin.iOSでWebClientを試した。(例外処理対応)

昨日のxamarin.iOSでWebClientを試しただと、通信できない環境でアプリが落ちたので、例外処理を入れて対応。

using System;
using System.Drawing;
using MonoTouch.UIKit;

using System.Net;

namespace UIKitExample
{
    public class UIViewExample : UIViewController
    {

        public UIViewExample ()
        {
            this.View.BackgroundColor = new UIColor (1.0f, 1.0f, 1.0f, 1.0f);           

            UILabel uilbl = new UILabel (new RectangleF (10.0f, 10.0f, 300.0f, 30.0f));
            uilbl.Text = "init";

            UIButton uiBtn = new UIButton (UIButtonType.RoundedRect);
            uiBtn.Frame = new RectangleF (10.0f, 40.0f, 300.0f, 30.0f);
            uiBtn.SetTitle("download button", UIControlState.Normal);
            uiBtn.TouchUpInside += (sender, e) => {
                WebClient webClient = new WebClient();
                //try~catchで処理を囲む。
                try {
                    uilbl.Text = webClient.DownloadString(new Uri("http://mitsugeek.net/xamarin/text.txt"));
                } catch(Exception ex){
                    uilbl.Text = ex.Message;
                }
            };

            UIButton uiBtnClear = new UIButton (UIButtonType.RoundedRect);
            uiBtnClear.Frame = new RectangleF (10.0f, 80.0f, 300.0f, 30.0f);
            uiBtnClear.SetTitle("clear button", UIControlState.Normal);
            uiBtnClear.TouchUpInside += (sender, e) => {
                uilbl.Text = "init";
            };

            this.View.AddSubviews (uilbl, uiBtn, uiBtnClear);
        }
    }
}

結果。

f:id:mitsugi-bb:20130305072419p:plain

NameResolutionFailureというエラーが発生してますね。try~catchで問題なくアプリは落ちなくなりました。

WebRequestの例外はこのへんが役に立つかもしれません。