Reputation: 1759
I want to make a helper class that handles the Geocoding and ReverseGeoCoding in my app.
My challenge is that the following line of code does not actually seem to await the result from the call.
var possibleAddresses = await iobj_Geocoder.GetAddressesForPositionAsync(pobj_Position);
Control is returned to the calling event before the address results are retrieved. Any help in how to make this work would be greatly appreciated.
Help Class Code:
using System.Linq;
using Xamarin.Forms.Maps;
namespace MapProblems
{
public class MapHelper
{
private Geocoder iobj_Geocoder;
public string Address { get; set; }
public MapHelper()
{
iobj_Geocoder = new Geocoder();
}
public async void GeoCodeAddress(Position pobj_Position)
{
var possibleAddresses = await iobj_Geocoder.GetAddressesForPositionAsync(pobj_Position);
Address = possibleAddresses.ToList()[0];
}
}
}
Main page that calls the helper class C# file:
using System;
using System.Diagnostics;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
namespace MapProblems
{
public partial class MainPage : ContentPage
{
MapHelper iobj_MapHelper;
public MainPage()
{
InitializeComponent();
iobj_MapHelper = new MapHelper();
this.Appearing += MainPage_Appearing;
}
private async void MainPage_Appearing(object sender, EventArgs e)
{
Device.BeginInvokeOnMainThread(() =>
{
iobj_MapHelper.GeoCodeAddress(new Position(38.9047, -077.0310));
}
);
Debug.WriteLine("Address: " + iobj_MapHelper.Address);
}
}
}
So the end result of this example is Address is any empty string when the Debug.WriteLine code executes.
Any assistance would be greatly appreciated.
Upvotes: 0
Views: 1142
Reputation: 3266
Because your GeoCodeAddress method is async void, your code has no way of knowing when it is finished. Try making it an async Task:
public async Task<string> GeoCodeAddress(Position pobj_Position)
{
var possibleAddresses = await iobj_Geocoder.GetAddressesForPositionAsync(pobj_Position);
return possibleAddresses.ToList()[0];
}
Then you can call it like so:
private async void MainPage_Appearing(object sender, EventArgs e)
{
var address = await iobj_MapHelper.GeoCodeAddress(new Position(38.9047, -077.0310));
Debug.WriteLine("Address: " + address);
}
Also, make sure you try/catch in the async void methods, as exceptions in there will crash your app if they go unhandled.
Upvotes: 1