1

I'm newer in iOS development.

I writing app for iOS on Xamarin C# I want to parse text from URL via GET request (JSON)

When I write Android app, I have this code and it work's

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);



}

I try to use this code in iOS

I have this code

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

}
}

I have this error:

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

Where i need to write async, or what is my mistake?

  • Could you please provide a Minimal, Complete, and Verifiable example (http://stackoverflow.com/help/mcve)? It is hard to debug your problem remotely without more context (i.e, in which class is your code located?) See also http://ericlippert.com/2014/03/05/how-to-debug-small-programs/ :) – pmbanka Dec 15 '15 at 15:13

2 Answers2

3

Your problem lies in line

JsonValue json = await FetchAsync(url2);

which is an equivalent of calling await in the constructor:

private JsonValue json;

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

which is incorrect, since you cannot put async on your constructor to allow using await inside.

So, what can you do in such situation? This topic was already discussed on SO and I agree with 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.

Community
  • 1
  • 1
pmbanka
  • 1,902
  • 17
  • 24
  • I don't understand what you mean. `this code works well` <- which code do you refer to? Your problem is not related to `FetchAsync` method, rather to the place where you try to call it (using `await` keyword). – pmbanka Dec 15 '15 at 14:49
0

Just write this

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