c# - 异步错误 Xamarin iOS

标签 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;
}

}
}

我有这个错误:

Error CS4033: The await' operator can only be used when its containing method is marked with theasync' modifier (CS4033)

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

最佳答案

你的问题在于行

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 :

The best solution is to acknowledge the asynchronous nature of the download and design for it.

In other words, decide what your application should look like while the data is downloading. Have the page constructor set up that view, and start the download. When the download completes update the page to display the data.

关于c# - 异步错误 Xamarin iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34289918/

相关文章:

xaml - "The type or namespace name ' 应用程序 ' could not be found"Xamarin 表单

ios - Xamarin iOS - 是否可以将 "Unified- Single View"项目定位到 iOS 6.x?

c# - 如何在 Xamarin iOS SQLite 中添加 SQLiteOpenFlags.FullMutex 标志

c# - 我怎样才能用鼠标围绕播放器旋转相机?

ios - Swift - 占位符长文本 - 切中间

ios - ReactiveCocoa -如何并行处理多个独立信号?

ios - PWA - iOS 更改状态栏颜色

c# - 服务器抛出异常。 (HRESULT : 0x80010105 (RPC_E_SERVERFAULT)) 的异常

c# - 难以理解重载类构造函数的语法

c# - 从 C# 打印信封