2013-09-24 35 views
1

嘗試在Xamarin for iOS中發送某些WebRequest時出現此錯誤。發送webRequest時出錯

我想登錄到一個網站,它完美地在Windows客戶端的C#visual studio中工作,但對於iOS,它給了我這個錯誤。

Unhandled Exception: 
MonoTouch.UIKit.UIKitThreadAccessException: UIKit Consistency error: you are calling a UIKit method that can only be invoked from the UI thread. 
    at MonoTouch.UIKit.UIApplication.EnsureUIThread() [0x00019] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:49 
    at MonoTouch.UIKit.UITextField.get_Text() [0x00000] in /Developer/MonoTouch/Source/monotouch/src/UIKit/UITextField.g.cs:919 
    at virtualNAX.virtualNAXViewController.SendPost (IAsyncResult Result) [0x00031] in /Users/Emil/Projects/virtualNAX/virtualNAX/virtualNAXViewController.cs:69 
    at System.Net.WebAsyncResult.CB (System.Object unused) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebAsyncResult.cs:151 

在線68:

Post.Write("email=" + username.Text + "&password=" + password.Text + "&remember=on&redir=index.php%2Fprofile%2F&action=login&submit=+Log+in+"); 

如果這裏需要的是我所有的代碼吧:

public void sendData() 
{ 

    HttpWebRequest Web = (HttpWebRequest)WebRequest.Create(dataurl); 
    Web.ContentType = "application/x-www-form-urlencoded"; 
    var cookies = new CookieContainer(); 
    Web.Method = "POST"; 
    Web.CookieContainer = cookies; 
    Web.BeginGetRequestStream(new AsyncCallback(SendPost), Web); 
} 

void SendPost(IAsyncResult Result) 
{ 
    HttpWebRequest Web = (HttpWebRequest)Result.AsyncState; 
    var Post = new StreamWriter(Web.EndGetRequestStream(Result)); 


    Post.Write("email=" + username.Text + "&password=" + password.Text + "&remember=on&redir=index.php%2Fprofile%2F&action=login&submit=+Log+in+"); 
    Post.Close(); 
    Web.BeginGetResponse(new AsyncCallback(GetData), Web); 
} 


void GetData(IAsyncResult Result) 
{ 
    HttpWebRequest Web = (HttpWebRequest)Result.AsyncState; 

    string forside = new StreamReader(Web.EndGetResponse(Result).GetResponseStream()).ReadToEnd(); 

    forside = WebUtility.HtmlDecode(forside); 

    if (forside.Contains ("Welcome back")) { 
     NSUserDefaults.StandardUserDefaults.SetString ("sandt", "logind"); 
     this.PerformSegue ("toMain", this); 
    } else if (forside.Contains ("<div id=\"login_fail\">")) { 
     using (UIAlertView alert = new UIAlertView ("Error", "The entered information was incorrect.\n\nPlease try again", null, "OK", null)) { 
      alert.Show(); 
     } 
    } else { 
     using (UIAlertView alert = new UIAlertView ("Error", "An unexpected error has occured.\n\nPlease try again later", null, "OK", null)) { 
      alert.Show(); 
     } 
    } 
} 

回答

2

如果 '用戶名' 和 '密碼' 的UI控件,然後你不能從後臺線程訪問它們。在調用方法之前,您需要獲取它們的值並將它們存儲在類變量中(或將它們作爲參數傳遞)。