启动StartUpdatingLocation()后,运行另一种方法-每次更新位置

时间:2019-07-17 03:52:20

标签: ios xamarin xamarin.forms

启动StartUpdatingLocation()后,运行另一种方法-每次更新位置。

我尝试在MethodToRun()中调用public LocationManager ()方法

public LocationManager()
        {
           this.locMgr = new CLLocationManager
           {
               PausesLocationUpdatesAutomatically = false
           };
           locMgr.AllowsBackgroundLocationUpdates = true;
           locMgr.DesiredAccuracy = 1;
           locMgr.DistanceFilter = 1;
           locMgr.StartUpdatingLocation();

MethodToRun();

}

async public void MethodToRun(){ 
// here I send the data to the server
// code ...
}

但是数据仅发送到服务器一次。

public LocationManager()
        {
           this.locMgr = new CLLocationManager
           {
               PausesLocationUpdatesAutomatically = false
           };
           locMgr.AllowsBackgroundLocationUpdates = true;
           locMgr.DesiredAccuracy = 1;
           locMgr.DistanceFilter = 1;
           locMgr.StartUpdatingLocation();
}

async public void MethodToRun(){ 
// here I send the data to the server
// code ...
}

每次位置数据更新时,我都需要发送数据。

1 个答案:

答案 0 :(得分:1)

您需要实现ICLLocationManagerDelegate实例并将其分配给您创建的CLLocationManager实例。

ICLLocationManagerDelegate中,有一个来自位置管理器的回调,名为UpdatedLocation(对象是locationManager:didUpdateToLocation:fromLocation:)。

因此,将ICLLocationManagerDelegate添加到现有的类中或新建一个类并实现UpdatedLocation

public class ALocationDelegate : NSObject, ICLLocationManagerDelegate
{
    [Export("locationManager:didUpdateToLocation:fromLocation:")]
    public void UpdatedLocation(CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation)
    {
        // do something with the updated location (newLocation)
    }
}

现在在您的CLLocationManager实例上,分配该委托的现有实例(或创建一个新实例):

locMgr.Delegate = new ALocationDelegate();

re:https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate