background.jpg
項目配置
-
1: 需在項目配置中開啟如下權(quán)限
setting - 2:在info.plist中添加
NSLocationAlwaysAndWhenInUseUsageDescription
及NSLocationWhenInUseUsageDescription
實現(xiàn)部分代碼
demo點這里
//定位 相關(guān)參數(shù)設(shè)置
- (CLLocationManager *)locManager
{
if (!_locManager) {
_locManager = [[CLLocationManager alloc] init];
if ([_locManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
_locManager.allowsBackgroundLocationUpdates = YES;
}
_locManager.pausesLocationUpdatesAutomatically = NO;
_locManager.distanceFilter = kCLDistanceFilterNone;
_locManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
}
return _locManager;
}
- (void)startLocation
{
if ([CLLocationManager locationServicesEnabled] == NO) {
NSLog(@"locationServicesEnabled false");
} else {
CLAuthorizationStatus authorizationStatus= [CLLocationManager authorizationStatus];
if(authorizationStatus == kCLAuthorizationStatusDenied || authorizationStatus == kCLAuthorizationStatusRestricted) {
NSLog(@"authorizationStatus failed");
} else {
NSLog(@"authorizationStatus authorized");
self.locManager.delegate = self;
[self.locManager requestAlwaysAuthorization];
// [self.locManager requestWhenInUseAuthorization];
[self.locManager startUpdatingLocation];
}
//回調(diào)
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
if (![self canUpload]) return;
CLLocation *loc = locations.firstObject;
NSLog(@"----- i = %d, 維度: %f, 經(jīng)度: %f", i++, loc.coordinate.latitude, loc.coordinate.longitude);
//上傳定位
[self uploadLocation:loc.coordinate];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"定位失敗: %@", error);
}
- (BOOL)canUpload
{
CFTimeInterval t = CACurrentMediaTime();
if (t - self.lastUpdateTime > _interval) {
self.lastUpdateTime = t;
return YES;
}
return NO;
}
效果圖
foreground.png
lock.jpg
后言
由于截圖是在位置不變的情況下進行的測試,位置不變邦投,定位回調(diào)會間隔有點長,可能不會每60s(所設(shè)置的時間間隔)就回調(diào)一次屯援, 但是如果在室外位置移動的情況及設(shè)置 _locManager.desiredAccuracy = kCLLocationAccuracyBest;
的情況下念脯, 幾乎可以達到每秒定位回調(diào)成功一次。