iOS后台定时定位

首先在你想要使用定位功能的ViewController 导入头文件

#import "LocationTracker.h"

然后声明两个成员变量:

@property LocationTracker * locationTracker;
@property (nonatomic) NSTimer* locationUpdateTimer;

之后写一个方法配置LocationTraker:

- (void)setUpLocationTraker
{
    UIAlertView * alert;
    
    //We have to make sure that the Background App Refresh is enable for the Location updates to work in the background.
    if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusDenied){
        
        alert = [[UIAlertView alloc]initWithTitle:@""
                                          message:@"The app doesn't work without the Background App Refresh enabled. To turn it on, go to Settings > General > Background App Refresh"
                                         delegate:nil
                                cancelButtonTitle:@"Ok"
                                otherButtonTitles:nil, nil];
        [alert show];
        
    }else if([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusRestricted){
        
        alert = [[UIAlertView alloc]initWithTitle:@""
                                          message:@"The functions of this app are limited because the Background App Refresh is disable."
                                         delegate:nil
                                cancelButtonTitle:@"Ok"
                                otherButtonTitles:nil, nil];
        [alert show];
        
    } else{
        
        self.locationTracker = [[LocationTracker alloc]init];
        [self.locationTracker startLocationTracking];
        
        //Send the best location to server every 60 seconds
        //You may adjust the time interval depends on the need of your app.
        // 设定向服务器发送位置信息的时间间隔
        NSTimeInterval time = 300; // 5分钟
        
        // 开启计时器
        self.locationUpdateTimer =
        [NSTimer scheduledTimerWithTimeInterval:time
                                         target:self
                                       selector:@selector(updateLocation)
                                       userInfo:nil
                                        repeats:YES];
    }
}

上面计时器每隔300s运行一次“updateLocation”方法,该方法的实现如下:

- (void)updateLocation {
    NSLog(@"开始获取定位信息...");
    // 向服务器发送位置信息
    [self.locationTracker updateLocationToServer];
}

上面的updateLocationToServer方法就是你向服务器发送信息的方法了,这个方法需要你依照自己的需求进行改动打开“LocationTraker.m”文件找到该方法:

//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

你可能感兴趣的:(iOS后台定时定位)