开启定位服务

2016-05-27  本文已影响46人  全民同學

开启定位步骤

[TOC]

第一步: 开启后台模式,选中定位选择project –> capabilities–>Backgorund Modes –> Location updates 如图: enter image description here

第二步: 在info.list 文件中添加如下配置:(添加定位权限,ios8之后需要添加,否则无法定位)

<key>NSLocationWhenInUseUsageDescription</key>   
<string>YES</string>    
<key>NSLocationAlwaysUsageDescription</key>        
<string>YES</string>

第三步:Appdelegate中代码1.引入头文件,定义全局变量

#import<CoreLocation/CoreLocation.h> 
@interface AppDelegate () {            
    CLLocationManager * _locationManager; 
}
 @end

2.didFinishLaunchingWithOptions中进行初始化(调用初始化方法),初始化方法如下:

-(void) createLocationManager{ 
      _locationManager = [[CLLocationManager alloc] init]; 
  if ([_locationManager  respondsToSelector:@selector(requestAlwaysAuthorization)]) {       
      [_locationManager requestAlwaysAuthorization]; 
  }
 if ([_locationManager   respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {     
      [_locationManager setAllowsBackgroundLocationUpdates:YES];
 }
   _locationManager.pausesLocationUpdatesAutomatically = NO; 
}

3.在applicationDidEnterBackground(进入后台)方法中执行启动定位服务
- (void)applicationDidEnterBackground:(UIApplication *)application {
[_locationManager startUpdatingLocation];
}

上一篇下一篇

猜你喜欢

热点阅读