在iOS 7中的简单ViewController中获取用户位置(didUpdateLocation)

时间:2013-12-16 13:15:54

标签: ios iphone objective-c core-location cllocationmanager

如何在iOS 7中的简单ViewController中获取用户位置? 我试过这种方式,但是在调试时我发现没有调用didUpdateLocation方法:

在MyViewController.h中:

#import <CoreLocation/CoreLocation.h>
@interface MyViewController : UIViewController <CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;   
}

在MyViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    //locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters; // 100 m
    [locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *newLocation = [locations lastObject];
    NSLog(@"NewLocation %f %f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Failed %ld",(long)[error code]);

}

didUpdateLocations未被调用,但在日志中称为didFailWithError:“失败0”。请帮帮我!

2 个答案:

答案 0 :(得分:2)

首先检查您确实拥有有效的WiFi和3G连接

然后

1)转到设置并重置您的位置服务

2)重置您的网络设置

如果在模拟器中,则检查是否为默认位置集。 This链接会显示。

答案 1 :(得分:1)

CLLocation经理说

kCLAuthorizationStatusNotDetermined = 0, // User has not yet made a choice with regards to this application
kCLAuthorizationStatusRestricted,        // This application is not authorized to use location services.  Due
                                         // to active restrictions on location services, the user cannot change
                                         // this status, and may not have personally denied authorization
kCLAuthorizationStatusDenied,            // User has explicitly denied authorization for this application, or
                                         // location services are disabled in Settings
kCLAuthorizationStatusAuthorized         // User has authorized this application to use location services

在您的情况下,CLAuthorizationStatus 0表示您不允许应用访问位置服务。