【发布时间】:2013-03-27 10:41:54
【问题描述】:
我正在开发一个启用了ARC 的iOS 6.1 iPhone app,它将使用CLLocationManager 来跟踪设备位置。
更新
我有一个DestinationViewController,它实现了CLLocationManagerDelegate。它创建CLLocationManager 并进行设置。我已将CoreLocation framework 导入到我的项目中。
我尝试了很多调试,可以看到 CLLocationManager 已创建并且没有错误出现。但问题是[CLLocationManager authorizationStatus] 是kCLAuthorizationStatusNotDetermined
在[self.locationManager startUpdatingLocation]; 之前和之后。
所以没有提示询问是否允许使用此应用的位置服务。因为这个方法永远不会被触发。
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:
(NSArray *)locations
我还尝试在网上搜索几个小时以寻找类似的示例,但没有运气。来自 DestinationViewController 的代码发布在下面。
界面
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@interface DestinationViewController : UIViewController <CLLocationManagerDelegate>
实施
#import "DestinationViewController.h"
@interface DestinationViewController ()
@property (strong, nonatomic) CLLocationManager *locationManager;
@end
@implementation DestinationViewController
// Initializer
- (CLLocationManager *)locationManager
{
if (!_locationManager) {
_locationManager = [[CLLocationManager alloc] init];
}
return _locationManager;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self startLocation];
}
- (void)startLocation
{
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 1;
NSString *error;
if (![CLLocationManager locationServicesEnabled]) {
error = @"Error message";
}
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status == kCLAuthorizationStatusRestricted ||
status == kCLAuthorizationStatusDenied ||) {
error = @"Error message";
}
if (error) {
NSLog(error);
}
else
{
status = [CLLocationManager authorizationStatus];
self.locationManager.pausesLocationUpdatesAutomatically = NO;
[self.locationManager startUpdatingLocation];
status = [CLLocationManager authorizationStatus];
NSLog(@"CLLocationManager is %@", self.locationManager);
NSLog(@"Location is %@", self.locationManager.location);
[self updateUI];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations
{
CLLocation *recentLocation = [locations lastObject];
NSLog(@"Found location");
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError");
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
NSLog(@"Change in authorization status");
}
【问题讨论】:
-
这是在模拟器还是设备上?如果是模拟器,您是否允许 XCode 模拟该位置?
-
两种都试过了。我创建了一个自定义位置并尝试进行高速公路行驶
-
您可以尝试实现已弃用的
locationManager:didUpdateToLocation:fromLocation:并查看它是否被调用? -
我也试过了。实际上,当我尝试运行 Apple Maps 应用程序时,现在我的模拟器显示“无法确定位置”。如果我在设置中查看,则允许应用获取位置。
-
您是否检查并查看您在“didFailWithError”中遇到了什么样的错误?因为这将有助于确定您的方法未触发的原因。
标签: iphone ios objective-c core-location cllocationmanager