您的位置:首页 > 移动开发 > IOS开发

ios无法定位CLLocationManager Delegate方法不能被调用的问题

2016-02-23 10:51 561 查看
最近使用ios定位功能,但是总是定位不成功,不能获取定位数据,找了好久原因,终于发现问题所在,原来是ios8之前的规则已经不适用了。

先从ios developer library 中找到相关的说明。

You must call this method(

-
requestWhenInUseAuthorization) or the
requestAlwaysAuthorization
method
prior to using location services.


Knowing When to Start Location Services

Apps that use location services should not start those services until they’re needed. With a few exceptions, avoid starting location services immediately at launch time or before such services might reasonably be used. Otherwise you might raise questions in
the user’s head about how your app uses location data. The user knows when your app starts location services because the first time your app starts the service, the system prompts the user for permission to use it. Waiting until the user performs a task that
actually requires those services helps build trust that your app is using them appropriately. Another way to build trust is to include the NSLocationAlwaysUsageDescriptionor NSLocationWhenInUseUsageDescription key
in your app’s
Info.plist
file and set the value of that key to a string that describes how your app intends to use location data. If you call
the
requestWhenInUseAuthorization
method
without including one of these keys, the system ignores your request.

To configure and use a
CLLocationManager
object
to deliver events:

Always request authorization to use location services and check to see whether the desired services are available as described in Requesting
Permission to Use Location Services.

Create an instance of the
CLLocationManager
class
and store a strong reference to it somewhere in your app.

Keeping a strong reference to the location manager object is required until all tasks involving that object are complete. Because most location manager tasks run asynchronously, storing your location manager in a local variable is insufficient.

Assign a custom object to the
delegate
property.
This object must conform to the
CLLocationManagerDelegate
protocol.

Configure any additional properties relevant to the desired service.

Call the appropriate start method to begin the delivery of events.

解决方法:

首先在.h定义一个属性:

@property (nonatomic, strong) CLLocationManager * locationManager;

在viewDidLoad中创建变量

if (self.locationManager == nil) {
self.locationManager = [[CLLocationManager alloc]init];
}

self.locationManager.delegate = self;
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 8.0) {
[self.locationManager requestWhenInUseAuthorization];
}

[self.locationManager startUpdatingLocation];

下面两个需要注意的点:一个是[self.locationManager
requestWhenInUseAuthorization];询问用户是否允许该应用使用定位服务。
另外一个,需要到info.plist中添加一个Key:NSLocationWhenInUsageDescription。加上这两个地方,定位服务就好了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: