標籤:
第一步,開啟後台模式,選中定位,選擇project --> capabilities-->Backgorund Modes --> Location updates
Paste_Image.png
第二步,在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
iOS後台定位,即時向伺服器發送最新位置