開(kāi)啟后臺(tái)定位,實(shí)時(shí)向服務(wù)器發(fā)送最新位置
第一步亚情,開(kāi)啟后臺(tái)模式妄痪,選中定位,選擇project --> capabilities-->Backgorund Modes --> Location updates 如圖:
第二步楞件,在info.list 文件中添加如下配置:
允許 http 請(qǐng)求 衫生,ios 9 之后需要添加,便于向服務(wù)器發(fā)送請(qǐng)求
?<key>NSAppTransportSecurity</key> ?
<dict>
<key>NSAllowsArbitraryLoads</key> ?
<true/>
? </dict>
添加定位權(quán)限土浸,ios8之后需要添加罪针,否則無(wú)法定位
?<key>NSLocationWhenInUseUsageDescription</key>?
<string>YES</string>
?<key>NSLocationAlwaysUsageDescription</key>?
<string>YES</string>
第三步,代碼如下:
#import "ViewController.h"?
@interface ViewController ()?
@end??
@implementation ViewController?
- (void)viewDidLoad
{
? [super viewDidLoad]; ?
self.view.backgroundColor = [UIColor whiteColor]; ?
self.title = @"后臺(tái)定位"; ?
self.locationManager = [[CLLocationManager alloc] init]; ?
self.locationManager.delegate = self; ?
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest]; ?
if ([[UIDevice currentDevice].systemVersion floatValue] > 8)
{?
/** 請(qǐng)求用戶權(quán)限:分為:只在前臺(tái)開(kāi)啟定位 /在后臺(tái)也可定位栅迄, */?
/** 只在前臺(tái)開(kāi)啟定位 */?
// [self.locationManager requestWhenInUseAuthorization];?
/** 后臺(tái)也可以定位 */ ?
[self.locationManager requestAlwaysAuthorization]; ?
} ?
if ([[UIDevice currentDevice].systemVersion floatValue] > 9)
{?
/** iOS9新特性:將允許出現(xiàn)這種場(chǎng)景:同一app中多個(gè)location manager:一些只能在前臺(tái)定位站故,另一些可在后臺(tái)定位(并可隨時(shí)禁止其后臺(tái)定位)皆怕。
*/ ?
[self.locationManager setAllowsBackgroundLocationUpdates:YES];?
}
? /** 開(kāi)始定位 */ ?
[self.locationManager startUpdatingLocation];
?}?
#pragma mark - 定位代理方法
?- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{ ?
CLLocation *loc = [locations objectAtIndex:0];
? NSLog(@"經(jīng)緯度 %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];
?}
@end
?```
至此毅舆,完成后臺(tái)實(shí)時(shí)定位功能西篓,并向服務(wù)器發(fā)送請(qǐng)求成功!