iphone - 使用 webrequest 和 uialertview 在 MonoTouch 中线程化

标签 iphone ios multithreading xamarin.ios monodevelop

我访问一个网站并使用 HttpWebRequest 检索一些数据,并且我需要一个带有 UIActivityIndi​​catorViewUIAlertView 在它检索所述数据时显示。但是,它只会使屏幕变暗并且不会显示警报,直到为时已晚。我在这里阅读了其他与线程相关的问题,但不知道如何解决这个问题。我尝试使用 ThreadPool、InvokeOnMainThread、Tasks,所有这些都没有用。

编辑:

HttpWebRequest url = (HttpWebRequest)WebRequest.Create ("maps.googleapis.com/maps/api/place/search/..); 

HttpWebResponse webResp = (HttpWebResponse)url.GetResponse (); JsonValue jVal = 

JsonObject.Load (webResp.GetResponseStream ()); 

JsonObject jObj = (JsonObject)jVal; 

我有上面的代码,如果它适合我​​的格式,我如何将其转换为使用 WebClient?您还能从中获取 JSON 等信息吗?

最佳答案

使用 WebClient 和其中之一的 *Async 方法通常比使用 HttpWebRequest 更容易(并且更不容易出错)。

这是一个下载和显示小图像的示例。

WebClient client = new WebClient ();
var wait = new UIActivityIndicatorView (View.Bounds);
client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => {
    byte[] result = e.Result;
    if (result != null) {
        NSData data = NSData.FromArray (e.Result);
        UIImage img = UIImage.LoadFromData (data);
        InvokeOnMainThread (delegate {
            ShowImage (img);
            wait.StopAnimating ();
        });
    }
};
wait.StartAnimating ();
client.DownloadDataAsync (new Uri (url));

编辑(更新问题)

对于流,您可以使用 WebClient.OpenReadAsyncOpenReadCompleted事件。

关于iphone - 使用 webrequest 和 uialertview 在 MonoTouch 中线程化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12624470/

相关文章:

ios - 如何在 Core Data 中保存用户偏好?

ios - 为什么 "self"在我的 QueryOperation 中阻止来自 CloudKit 的数据

java - 处理多线程以从结果集中创建受密码保护的 Excel

java - 多线程使用中的变量声明,Java [内存泄漏问题]

iphone - 如何在 UIView 中获取父级导航 Controller

iphone - 如何安全地停止 AVAudioPlayer

ios - 流式传输时 iPhone 6S 出现音频问题

ios - accessoryButtonTappedForRowWithIndexPath 不适用于自定义按钮或标签

c - 有透明的网络加速库吗?

iphone - 无线网络应用