异步错误Xamarin iOS

时间:2015-12-15 12:58:13

标签: c# ios xamarin xamarin.ios

我在iOS开发方面比较新。

我在Xamarin C上编写iOS应用# 我想通过GET请求(JSON)从URL解析文本

当我编写Android应用程序时,我有这个代码,它可以正常运行

string url2 = "http://new.murakami.ua/?mkapi=getActions";
  JsonValue json = await FetchAsync(url2);
ParseAndDisplay(json);
private async Task<JsonValue> FetchAsync(string url)
{
  // Create an HTTP web request using the URL:
  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
  request.ContentType = "application/json";
  request.Method = "GET";

  // Send the request to the server and wait for the response:
  using (WebResponse response = await request.GetResponseAsync())
  {
    // Get a stream representation of the HTTP web response:
    using (Stream stream = response.GetResponseStream())
    {
      // Use this stream to build a JSON document object:
      JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
      //dynamic data = JObject.Parse(jsonDoc[15].ToString);
      //Console.Out.WriteLine("Response: {0}", jsonDoc[0].ToString);


      // Return the JSON document:
      return jsonDoc;
    }
  }
}

private void ParseAndDisplay(JsonValue json)
{


  ImageView imagen = FindViewById<ImageView>Resource.Id.image1);
  TextView titlename = FindViewById<TextView>Resource.Id.title1);
  //TextView datename = FindViewById<TextView>Resource.Id.date1);
  imagen.Click += delegate
  {
    var intent358 = new Intent(this, typeof(AkciiActivity1));
    StartActivity(intent358);
  };
  titlename.Click += delegate
  {
    var intent359 = new Intent(this, typeof(AkciiActivity1));
    StartActivity(intent359);
  };
  JsonValue firstitem = json[0];
  //Console.Out.WriteLine(firstitem["post_title"].ToString());

  titlename.Text = firstitem["title"];
  //datename.Text = firstitem["date"];
  var imageBitmap2 = GetImageBitmapFromUrl(firstitem["img"]);
  imagen.SetImageBitmap(imageBitmap2);



}

我尝试在iOS中使用此代码

我有这段代码

namespace murakami_kiev {

partial class ActionsViewController: UIViewController {
public ActionsViewController(IntPtr handle): base(handle) {
  }
  //aktions parser begin

string url2 = "http://new.murakami.ua/?mkapi=getActions";
JsonValue json = await FetchAsync(url2);

private async Task < JsonValue > FetchAsync(string url) {
  // Create an HTTP web request using the URL:
  HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(new Uri(url));
  request.ContentType = "application/json";
  request.Method = "GET";

  // Send the request to the server and wait for the response:
  using(WebResponse response = await request.GetResponseAsync()) {
    // Get a stream representation of the HTTP web response:
    using(Stream stream = response.GetResponseStream()) {
      // Use this stream to build a JSON document object:
      JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
      //dynamic data = JObject.Parse(jsonDoc[15].ToString);
      //Console.Out.WriteLine("Response: {0}", jsonDoc[0].ToString);
      // Return the JSON document:
      return jsonDoc;
    }
  }
}

private void ParseAndDisplay(JsonValue json) {
  ImageView imagen = FindViewById < ImageView > (Resource.Id.image1);
  TextView titlename = FindViewById < TextView > (Resource.Id.title1);
  //TextView datename = FindViewById<TextView>(Resource.Id.date1);
  /*imagen.Click += delegate
        {
            var intent358 = new Intent(this, typeof(AkciiActivity1));
            StartActivity(intent358);
        };
        titlename.Click += delegate
        {
            var intent359 = new Intent(this, typeof(AkciiActivity1));
            StartActivity(intent359);
        };*/
  JsonValue firstitem = json[0];
  //Console.Out.WriteLine(firstitem["post_title"].ToString());


  titlename.Text = firstitem["title"];
  //datename.Text = firstitem["date"];
  var imageBitmap2 = GetImageBitmapFromUrl(firstitem["img"]);
  imagen.SetImageBitmap(imageBitmap2);
}

//aktions parser end
public override void ViewDidLoad() {
  base.ViewDidLoad();
  // Perform any additional setup after loading the view, typically from a nib.

  string actionsfirst = "Новая супер акция от мураками";
  Actions001.Text = actionsfirst;
}

}
}

我有这个错误:

  

错误CS4033:await' operator can only be used when its containing method is marked with the异步&#39;修饰语(CS4033)

我需要写异步,或者我的错误是什么?

2 个答案:

答案 0 :(得分:3)

你的问题在于

JsonValue json = await FetchAsync(url2);

这相当于在构造函数中调用await

private JsonValue json;

public ActionsViewController(IntPtr handle): base(handle) {
    json = await FetchAsync(url2); // Error!
}

这是不正确的,因为您无法在构造函数上放置async以允许在其中使用await

那么,在这种情况下你能做些什么呢? This topic was already discussed on SO我同意Stephen Cleary answer

  

最好的解决方案是确认下载和设计的异步性。

     

换句话说,确定在下载数据时应用程序应该是什么样子。让页面构造函数设置该视图,然后开始下载。下载完成后,更新页面以显示数据。

答案 1 :(得分:0)

请写下这个

public async override void ViewDidLoad() {
  base.ViewDidLoad();
  // Perform any additional setup after loading the view, typically from a nib.

string url2 = "http://new.murakami.ua/?mkapi=getActions";
JsonValue json = await FetchAsync(url2);

private async Task < JsonValue > FetchAsync(string url) {
  // Create an HTTP web request using the URL:
  HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(new Uri(url));
  request.ContentType = "application/json";
  request.Method = "GET";

  // Send the request to the server and wait for the response:
  using(WebResponse response = await request.GetResponseAsync()) {
    // Get a stream representation of the HTTP web response:
    using(Stream stream = response.GetResponseStream()) {
      // Use this stream to build a JSON document object:
      JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
      //dynamic data = JObject.Parse(jsonDoc[15].ToString);
      //Console.Out.WriteLine("Response: {0}", jsonDoc[0].ToString);
      // Return the JSON document:
      return jsonDoc;
    }
  }
}
  string actionsfirst = "Новая супер акция от мураками";
  Actions001.Text = actionsfirst;
}