1

我想写一个后台应用程序。在这个应用程序中,我有 currentUserLocation 一个由用户设置的位置。所以我想要计算这两个位置之间的距离,如果用户到达目的地或在指定范围内,则启动一个事件,如本地通知。

我有的

一个 ViewController 类(提供 MapView)

一个 MapView 类(提供地图)

   - (id)initWithFrame:(CGRect)frame
 {
      self = [super initWithFrame:frame];
         if (self) {
           self.map = [[MKMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];

           self.map.delegate = self;
          [self addSubview:self.map];

           self.locationManager = [[CLLocationManager alloc] init];
           self.locationManager.delegate = self;
           self.locationManager.pausesLocationUpdatesAutomatically = NO;
          self.locationManager.desiredAccuracy = [[[Manager getInstance]            returnValueForKey:@"GPS"] intValue];
  }

然后在 locationManager: didUpdateLocations: 方法

   - (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{


CLLocation *loc = [locations lastObject];

   // calculate the distance between two points

float d = acos(sin(self.mapPin.coordinate.latitude/ 180*M_PI) *sin(self.map.userLocation.coordinate.latitude/ 180*M_PI)
             + cos(self.mapPin.coordinate.latitude/ 180*M_PI) *cos(self.map.userLocation.coordinate.latitude/ 180*M_PI) *cos(self.map.userLocation.coordinate.longitude/180*M_PI - self.mapPin.coordinate.longitude/ 180*M_PI));

d = d * 6378.137;



// calculate the distance between two points also

CLLocationDistance dist = [self.map.userLocation.location  distanceFromLocation:loc];




if (UIApplication.sharedApplication.applicationState == UIApplicationStateActive ){


    [self calculateDistanz:loc.coordinate];
}else{


    NSLog(@"dist = %f",dist/1000);
    NSLog(@"d = %f",d);


    if (d <= self.range ) {

        [[UIApplication sharedApplication] cancelAllLocalNotifications];


        self.localNotif = [[UILocalNotification alloc] init];

        if (self.localNotif == nil)

            return;

        self.localNotif.timeZone = [NSTimeZone defaultTimeZone];
        self.localNotif.alertBody = @"Text";
        self.localNotif.alertAction = @"Stop";
        self.localNotif.soundName = @"Alarm.mp3";

        NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];


        self.localNotif.userInfo = infoDict;
        self.localNotif.hasAction = YES;

        [[UIApplication sharedApplication] presentLocalNotificationNow:self.localNotif];

    }

}

}

我还在 info.plist 中将该应用程序注册为本地更新的后台应用程序。所以问题是进入后台模式时计算停止。调用方法 -(void) locationManager: didUpdateLocations: 是因为日志语句显示在控制台中。我可以看到,此时,当应用程序进入后台模式时,变量 d 始终相同。直到应用程序处于活动状态,然后 d 正在更新。

我已经阅读和阅读了一个星期,但我找不到错误......也许你可以帮助谢谢帮助......

4

0 回答 0