【问题标题】:How do i get the current location in the background mode in iPhone?如何在 iPhone 的后台模式下获取当前位置?
【发布时间】:2012-05-20 04:43:48
【问题描述】:

我正在使用 CLLocationManager 获取当前位置,并且正在获取当前位置的纬度和经度值。我没有在我的应用程序中使用 Mapview。因此,每当更改当前位置时,我都想将当前位置更新到服务器。并且每 5 分钟我需要调用网络服务并在 后台模式和前台模式下将当前位置更新到服务器。

-(void) getCurrentLocation
{
    // To get the current location of the place
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone; //whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; //100 m
    //Start the location manager, then only updates the current location
    [locationManager startUpdatingLocation];
}

/In Location manager delegate method, if the location is updated it will call and get the values from the newLocation using CLLocation  
-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    CLLocation *location = [locationManager location];

    // Configure the new event with information from the location
    CLLocationCoordinate2D coordinate = [location coordinate];

    NSString *lat = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *lon = [NSString stringWithFormat:@"%f", coordinate.longitude];
    NSLog(@"dLatitude : %@", lat);
    NSLog(@"dLongitude : %@",lon);

    self.reverseGeocoder = [[[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate] autorelease];
    reverseGeocoder.delegate = self;
    [reverseGeocoder start];


    //Stop the location manager
    [locationManager stopUpdatingLocation];

}

每当更改位置时,我都想获取特定位置的纬度和经度。

谢谢!

【问题讨论】:

    标签: ios iphone objective-c cllocationmanager currentlocation


    【解决方案1】:

    如果您需要使用标准位置服务为用户提供持续的位置更新(即使在后台),您可以通过包含 UIBackgroundModes 键(使用“位置”值)声明您的应用需要后台位置服务) 在您应用的 Info.plist 文件中。

    【讨论】:

      【解决方案2】:

      将以下代码用于后台和前台任务。

          UIApplication *app = [UIApplication sharedApplication];
      
      bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask];
          bgTask = UIBackgroundTaskInvalid;
      }];
      
      [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(updateLocation) userInfo:nil repeats:YES];
      
      -(void)updateLocation{
      
          // write the code to update location here. this will execute even if in background or foreground
      }
      

      【讨论】:

        【解决方案3】:

        首先,如果您需要您的程序在前台和后台运行,请在项目的 info.plist 中添加所需的后台模式作为位置服务。获取位置作为 NSString 并尝试使用同步或异步类型将 URL 发布到服务器的 URL。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-17
          • 2016-03-14
          • 1970-01-01
          • 1970-01-01
          • 2011-11-21
          相关资源
          最近更新 更多