これはかなり一般的なシナリオであり、いくつかの異なる方法で解決できます。私の個人的な好みは、Xamarin.Formsプラグインで使用されているパターンに従うことです。 Geolocator Pluginが構成されているかを見てみましょう:
// Abstraction for the information you want to access in shared (PCL) code
public interface IGeolocator
{
event EventHandler<PositionEventArgs> PositionChanged;
...
}
ここで、イベントは、位置の更新を購読するIGeolocator
を使用して、任意のPCLコードの形で持って来ることができます。これはあなたがCLLocationManager
と聞いているようなものです。この情報を転送するために、IGeolocator
のiOS固有の実装では、CLLocationManager.LocationsUpdated
が発生するとPositionChanged
イベントが発生します。
manager.LocationsUpdated += OnLocationsUpdated;
...
void OnLocationsUpdated(object sender, CLLocationsUpdatedEventArgs e)
{
foreach (CLLocation location in e.Locations)
UpdatePosition(location);
...
}
// UpdatePosition copies the lat/long/etc into the PositionEventArgs and calls OnPositionChanged
void OnPositionChanged(PositionEventArgs e) => PositionChanged?.Invoke(this, e);
最後に、それはDependencyService.Get<IGeolocator>()
を使用してシングルトンまたはいずれかの共有コードで使われています:
try
{
// Singleton usage
var locator = CrossGeolocator.Current;
// DependencyService
// var locator = DepedencyService.Get<IGeolocator>();
locator.DesiredAccuracy = 50;
// Subscribing to event in shared code
locator.PositionChanged += OnPositionChanged;
}
catch(Exception ex)
{
...
}
このコードのすべてがhereを見つけることができます。また、このプラグインの使用を検討することもできます。それは役に立つかもしれない他の機能を持っています。 GitHubのページには、その使い方を示しています。
これはMessagingCenterの便利な使い方です。https://developer.xamarin.com/guides/xamarin-forms/messaging-center/ – Jason
PCLプロジェクトでどのように依存サービスを呼び出しましたか? PCLプロジェクトで依存関係サービスを呼び出すと、緯度/経度の値を取得する必要があります。 –