iOS后台定位,实时向服务器发送最新位置
2015-09-29 本文已影响11061人
Lonely__M
第一步,开启后台模式,选中定位,选择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
至此,完成后台实时定位功能,并向服务器发送请求成功
记录点滴。
Tip
学习的路上总是曲折的,每个人都是从菜鸟过来的,遇到问题总是希望能够与他人沟通交流,而在各种群里问了问题就石沉大海,所以想建一个技术交流为主的群,遇到的问题可以记录下来分享给他人,方便了自己,也造就了他人,不管怎样,记录点滴,但愿与君共勉
*QQ群号:527377492 *
Paste_Image.png