首先在你想要使用定位功能的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<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];
}
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
// TODO: 在这里插入你向服务器发送请求的代码
lat = [NSString stringWithFormat:@"%f",self.myLocation.latitude];
lon = [NSString stringWithFormat:@"%f",self.myLocation.longitude];
// 根据用户输入的经纬度创建CLLocation对象
CLLocation *location = [[CLLocation alloc] initWithLatitude:[lat doubleValue] longitude:[lon doubleValue]];
// 反地理编码
// CLGeocoder *_geocoder;
// _geocoder = [[CLGeocoder alloc]init];
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks firstObject];
NSDictionary *addressDictionary = placemark.addressDictionary;
name = [addressDictionary objectForKey:@"Name"];
[self getHttp];
}];
//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)getHttp{
NSUserDefaults *appDefault =[NSUserDefaults standardUserDefaults];
NSString *phone = [appDefault objectForKey:@"phone"];
if(phone == nil){
NSLog(@"phone is nil");
return;
}
NSLog(@"phone----%@",phone);
// NSDictionary *dict = @{ @"a_infophone":phone,@"latitude":lat,@"longitude":lon,@"address":name,@"type":@"1"};
NSDictionary *dict = @{ @"a_infophone":phone,@"latitude":lat,@"longitude":lon,@"address":name};
NSLog(@"a_infophone---%@",dict[@"a_infophone"]);
NSLog(@"latitude---%@",dict[@"latitude"]);
NSLog(@"longitude---%@",dict[@"longitude"]);
NSLog(@"address---%@",dict[@"address"]);
// NSLog(@"type---%@",dict[@"type"]);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSString *url = POSITION_URI;
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", responseObject);
NSString *requestTmp = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"requestTmp---%@",requestTmp);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}