700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > iOS后台定位 实时向服务器发送最新位置

iOS后台定位 实时向服务器发送最新位置

时间:2019-12-27 03:05:16

相关推荐

iOS后台定位 实时向服务器发送最新位置

第一步,开启后台模式,选中定位,选择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:@"/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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。