在ios应用程序处于后台时将用户位置发送到服务器

在ios应用程序处于后台时将用户位置发送到服务器,ios,location,background-fetch,Ios,Location,Background Fetch,当我的应用程序处于后台模式时,请帮助我尝试将应用程序的当前位置发送到服务器 但经过一段时间后,位置更新方法是停止获取当前位置 - (void)startLocationTracking { NSLog(@"startLocationTracking"); if ([CLLocationManager locationServicesEnabled] == NO) { NSLog(@"locationServicesEnabled false");

当我的应用程序处于后台模式时,请帮助我尝试将应用程序的当前位置发送到服务器

但经过一段时间后,位置更新方法是停止获取当前位置

- (void)startLocationTracking
{
    NSLog(@"startLocationTracking");

    if ([CLLocationManager locationServicesEnabled] == NO)
    {
        NSLog(@"locationServicesEnabled false");
        UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled" message:@"You currently have all location services for this device disabled" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [servicesDisabledAlert show];
    } else
    {
        CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];

        if(authorizationStatus == kCLAuthorizationStatusDenied || authorizationStatus == kCLAuthorizationStatusRestricted){
            NSLog(@"authorizationStatus failed");
        } else {
            NSLog(@"authorizationStatus authorized");
            CLLocationManager *locationManager = [LocationTracker sharedLocationManager];
            locationManager.delegate = self;
            locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
            locationManager.distanceFilter = kCLDistanceFilterNone;

            if(IS_OS_8_OR_LATER) {
              [locationManager requestAlwaysAuthorization];
            }
            [locationManager startUpdatingLocation];
            [locationManager startMonitoringSignificantLocationChanges];
        }
    }
}


- (void)stopLocationTracking {
    NSLog(@"stopLocationTracking");

    if (self.shareModel.timer) {
        [self.shareModel.timer invalidate];
        self.shareModel.timer = nil;
    }

    CLLocationManager *locationManager = [LocationTracker sharedLocationManager];
    [locationManager stopUpdatingLocation];
    [locationManager stopMonitoringSignificantLocationChanges];
}

#pragma mark - CLLocationManagerDelegate Methods

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

    NSLog(@"locationManager didUpdateLocations");

    for(int i=0;i<locations.count;i++){
        CLLocation * newLocation = [locations objectAtIndex:i];
        CLLocationCoordinate2D theLocation = newLocation.coordinate;
        CLLocationAccuracy theAccuracy = newLocation.horizontalAccuracy;

        NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];

        if (locationAge > 30.0)
        {
            continue;
        }

        //Select only valid location and also location with good accuracy
        if(newLocation!=nil&&theAccuracy>0
           &&theAccuracy<2000
           &&(!(theLocation.latitude==0.0&&theLocation.longitude==0.0))){

            self.myLastLocation = theLocation;
            self.myLastLocationAccuracy= theAccuracy;

            NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
            [dict setObject:[NSNumber numberWithFloat:theLocation.latitude] forKey:@"latitude"];
            [dict setObject:[NSNumber numberWithFloat:theLocation.longitude] forKey:@"longitude"];
            [dict setObject:[NSNumber numberWithFloat:theAccuracy] forKey:@"theAccuracy"];

            //Add the vallid location with good accuracy into an array
            //Every 1 minute, I will select the best location based on accuracy and send to server
            [self.shareModel.myLocationArray addObject:dict];
        }
    }

    //If the timer still valid, return it (Will not run the code below)
    if (self.shareModel.timer) {
        return;
    }

    self.shareModel.bgTask = [BackgroundTaskManager sharedBackgroundTaskManager];
    [self.shareModel.bgTask beginNewBackgroundTask];

    //Restart the locationMaanger after 1 minute
    self.shareModel.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self
                                                           selector:@selector(restartLocationUpdates)
                                                           userInfo:nil
                                                            repeats:NO];

    //Will only stop the locationManager after 10 seconds, so that we can get some accurate locations
    //The location manager will only operate for 10 seconds to save battery
    if (self.shareModel.delay10Seconds) {
        [self.shareModel.delay10Seconds invalidate];
        self.shareModel.delay10Seconds = nil;
    }

    self.shareModel.delay10Seconds = [NSTimer scheduledTimerWithTimeInterval:10 target:self
                                                    selector:@selector(stopLocationDelayBy10Seconds)
                                                    userInfo:nil
                                                     repeats:NO];
}


//Stop the locationManager
-(void)stopLocationDelayBy10Seconds{
    CLLocationManager *locationManager = [LocationTracker sharedLocationManager];
    [locationManager stopUpdatingLocation];
    [locationManager stopMonitoringSignificantLocationChanges];

    NSLog(@"locationManager stop Updating after 10 seconds");
}


- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error
{
   NSLog(@"locationManager error:%@",error);
}


//Send the location to Server
- (void)updateLocationToServer {

    NSLog(@"updateLocationToServer");

    // Find the best location from the array based on accuracy
    NSMutableDictionary * myBestLocation = [[NSMutableDictionary alloc]init];

    for(int i=0;i<self.shareModel.myLocationArray.count;i++){
        NSMutableDictionary * currentLocation = [self.shareModel.myLocationArray objectAtIndex:i];

        if(i==0)
            myBestLocation = currentLocation;
        else{
            if([[currentLocation objectForKey:ACCURACY]floatValue]<=[[myBestLocation objectForKey:ACCURACY]floatValue]){
                myBestLocation = currentLocation;
            }
        }
    }
    NSLog(@"My Best location:%@",myBestLocation);

    //If the array is 0, get the last location
    //Sometimes due to network issue or unknown reason, you could not get the location during that  period, the best you can do is sending the last known location to the server
    if(self.shareModel.myLocationArray.count==0)
    {
        NSLog(@"Unable to get location, use the last known location");

        self.myLocation=self.myLastLocation;
        self.myLocationAccuracy=self.myLastLocationAccuracy;

    }else{
        CLLocationCoordinate2D theBestLocation;
        theBestLocation.latitude =[[myBestLocation objectForKey:LATITUDE]floatValue];
        theBestLocation.longitude =[[myBestLocation objectForKey:LONGITUDE]floatValue];
        self.myLocation=theBestLocation;
        self.myLocationAccuracy =[[myBestLocation objectForKey:ACCURACY]floatValue];
    }
    [self getUpdateLocation];
    NSLog(@"Send to Server: Latitude(%f) Longitude(%f) Accuracy(%f)",self.myLocation.latitude, self.myLocation.longitude,self.myLocationAccuracy);

    //TODO: Your code to send the self.myLocation and self.myLocationAccuracy to your server

    //After sending the location to the server successful, remember to clear the current array with the following code. It is to make sure that you clear up old location in the array and add the new locations from locationManager
    [self.shareModel.myLocationArray removeAllObjects];
    self.shareModel.myLocationArray = nil;
    self.shareModel.myLocationArray = [[NSMutableArray alloc]init];
}

-(void)getUpdateLocation
{
    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];

    dataMobile = [currentDefaults valueForKey:@"mobile"];
    dataCode = [currentDefaults valueForKey:@"code"];

    strMobile = [self getDecryptionMobile];
    strCode = [self getDecryptionCode];

    strToken = [NSString stringWithFormat:@"%@%@%@",@"Apple",strMobile,strCode];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSDictionary *params = @ {@"function" :@"map/location/insert",@"childIdEnc":[currentDefaults valueForKey:@"childIdEnc"], @"phoneId" : [currentDefaults valueForKey:@"phoneId"], @"latitude": [NSString stringWithFormat:@"%f",self.myLocation.latitude], @"longitude": [NSString stringWithFormat:@"%f",self.myLocation.longitude]};
    NSLog(@"params %@",params);

    [manager POST:@"https://api.familyconnect.net/call/?debug=1" parameters:params
          success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSDictionary *jsonList = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"JSON: %@", jsonList);
    }
          failure:
     ^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
     }];
}
-(无效)定位跟踪
{
NSLog(“惊人定位跟踪”);
如果([CLLocationManager locationServicesEnabled]==否)
{
NSLog(@“locationServicesEnabled false”);
UIAlertView*ServicesDisableAlert=[[UIAlertView alloc]initWithTitle:@“禁用位置服务”消息:@“您当前已禁用此设备的所有位置服务”委托:nil CancelButtontTitle:@“确定”其他按钮:nil];
[服务禁用警报显示];
}否则
{
CLAuthorizationStatus authorizationStatus=[CLLocationManager authorizationStatus];
如果(authorizationStatus==kCLAuthorizationStatusDenied | | authorizationStatus==kCLAuthorizationStatusRestricted){
NSLog(@“授权状态失败”);
}否则{
NSLog(“授权状态已授权”);
CLLocationManager*locationManager=[LocationTracker sharedLocationManager];
locationManager.delegate=self;
locationManager.desiredAccuracy=KCallocationAccuracyBestforNavigation;
locationManager.distanceFilter=KCLDistanceFilterOne;
如果(是8或更高版本){
[locationManager请求始终授权];
}
[locationManager startUpdatingLocation];
[locationManager开始监视重要的位置更改];
}
}
}
-(无效)停止位置跟踪{
NSLog(“stopLocationTracking”);
if(self.shareModel.timer){
[self.shareModel.timer invalidate];
self.shareModel.timer=nil;
}
CLLocationManager*locationManager=[LocationTracker sharedLocationManager];
[locationManager停止更新位置];
[locationManager停止监视重要的位置更改];
}
#pragma标记-CLLocationManagerDelegate方法
-(无效)位置管理器:(CLLocationManager*)管理器更新位置:(NSArray*)位置{
NSLog(@“locationManager didUpdateLocations”);
对于(int i=0;i 30.0)
{
继续;
}
//仅选择有效位置,并选择精度较高的位置
if(newLocation!=nil&&t精确度>0

&&准确性您似乎正在使用受此示例启发的代码

但本例在10秒后停止位置更新,以节省电池寿命。请参阅此注释

//Will only stop the locationManager after 10 seconds, so that we can get some accurate locations
//The location manager will only operate for 10 seconds to save battery
但如果配置正确,locationtracker还会创建一个计时器,以便在60秒内再次启动位置更新

基本上,它会收集10秒钟的位置更新,过滤掉最好的。60秒钟后,位置更新会重新开始。在上面的链接中,请参考
LocationAppDelegate
调用

//Send the best location to server every 60 seconds
//You may adjust the time interval depends on the need of your app.
NSTimeInterval time = 60.0;
self.locationUpdateTimer =
[NSTimer scheduledTimerWithTimeInterval:time
                                 target:self
                               selector:@selector(updateLocation)
                               userInfo:nil
                                repeats:YES];

此计时器导致“重新启动”位置更新。

UIAlertView
在iOS中不推荐使用。您可能希望更新到
UIAlertController
。方法如下:我的主要问题是关于位置更新,而不是UIAlertView。它被删除了UIAlertView。这就是为什么我作为注释而不是答案发布。@BKjadav我有同样的问题。我也使用了与您相同的方法低。你有什么解决办法吗……请你看看这个