标签:
第一步,开启后台模式,选中定位,选择project --> capabilities-->Backgorund Modes --> Location updates 如图:
第二步,在info.list 文件中添加如下配置:
允许 http 请求 ,ios 9 之后需要添加,便于向服务器发送请求
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
添加定位权限,ios8之后需要添加,否则无法定位
<key>NSLocationWhenInUseUsageDescription</key>
<string>YES</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>YES</string>
第三步,代码如下:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = [UIColor whiteColor]; self.title = @"后台定位"; self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; if ([[UIDevice currentDevice].systemVersion floatValue] > 8) { /** 请求用户权限:分为:只在前台开启定位 /在后台也可定位, */ /** 只在前台开启定位 */ // [self.locationManager requestWhenInUseAuthorization]; /** 后台也可以定位 */ [self.locationManager requestAlwaysAuthorization]; } if ([[UIDevice currentDevice].systemVersion floatValue] > 9) { /** iOS9新特性:将允许出现这种场景:同一app中多个location manager:一些只能在前台定位,另一些可在后台定位(并可随时禁止其后台定位)。 */ [self.locationManager setAllowsBackgroundLocationUpdates:YES]; } /** 开始定位 */ [self.locationManager startUpdatingLocation]; } #pragma mark - 定位代理方法 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { CLLocation *loc = [locations objectAtIndex:0]; NSLog(@"经纬度 %f %f ",loc.coordinate.latitude,loc.coordinate.longitude); NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://ac.ybjk.com/ua.php"]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // NSLog(@"response %@",response); NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"result %@",result); }]; [task resume]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
标签:
原文地址:http://www.cnblogs.com/weiboyuan/p/5135686.html