I am new to Xamarin and I am messing up with async and await. I am using ZXing to scan barcodes and having success when I just send the JSON and forget it, but if only that was good enough. I need to see the responses from the Server. I have achieved this but it not acting like I want it to. My goal is to Scan a barcode from a ScanPage then redirect to another page to get the response from the server. I tried to make a new overloaded constructor on a response page but I couldn't get it to work.
Here is the code that somewhat works:
public void Handle_OnScanResult(Result result) { if (_isScanning) { _isScanning = false; IsAnalyzing = false; if (App.ApiUrl != null) { DataService ds = new DataService(); var scanner = new { scan = new Scan() }; var newText = result.Text; scanner.scan.Sku = newText; scanner.scan.Timestamp = DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss"); scanner.scan.Employee = App.Employee; var myContent = JsonConvert.SerializeObject(scanner, Formatting.None); var buffer = Encoding.UTF8.GetBytes(myContent); var byteContent = new ByteArrayContent(buffer); byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); Device.BeginInvokeOnMainThread(async () => { var p = await ds.PostDataToService(App.ApiUrl, byteContent); await DisplayAlert(p.StatusCode.ToString(), await p.Content.ReadAsStringAsync(), "Ok"); await Navigation.PopAsync(); }); } } Thread.Sleep(2000); _isScanning = true; }
I hate that Thread.Sleep but the property of ZXing called IsScanning doesn't seem to work nor does the _isScanning bool I made.
I want to do something like this:
```
public void Handle_OnScanResult(Result result)
{
if (_isScanning)
{
_isScanning = false;
IsAnalyzing = false;
if (App.ApiUrl != null)
{
DataService ds = new DataService();
var scanner = new { scan = new Scan() };
var newText = result.Text;
scanner.scan.Sku = newText;
scanner.scan.Timestamp = DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss");
scanner.scan.Employee = App.Employee;
Navigation.PopAsync();
Navigation.PushAsync(new ResponsePage(scanner));
}
}
}
public ResponsePage(object scan) //ctor for new page { ConstructJSON(scan); PostDataToService(scan); DisplayResponseHere(); }
Sorry I am a noob. Thanks if you can help.
Nevermind, I completely redone my code and made separate classes for the jobs. Then I passed the object to the new page and did the work there.
Answers
Nevermind, I completely redone my code and made separate classes for the jobs. Then I passed the object to the new page and did the work there.