iOS位置问题 - 无法看到任何数据进入

时间:2013-08-29 12:35:59

标签: ios objective-c core-location

我是iOS编程的新手,并试图获取我当前的位置。我的主要应用代表是这样的,

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@class AWSViewController;

@interface AWSAppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) AWSViewController *viewController;
@property (strong, nonatomic) UINavigationController *navController;
@property (strong, nonatomic) NSMutableArray *cities;

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;

@end

在实现中,我有这两种方法,我从(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

调用getCurrentLocation

我可以在控制台上看到“开始获取位置”字样,之后我看不到任何其他内容。

-(void)getCurrentLocation {

    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    locationManager.distanceFilter = 500;
    [locationManager startUpdatingLocation];
    NSLog(@"Started to get locations");
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

    CLLocation *location = [locations lastObject];
    NSLog(@"Got Location");
    NSLog(@"latitude %+.6f, longitude %+.6f\n", location.coordinate.latitude, location.coordinate.longitude);
}

我在这里做错了什么? 感谢

3 个答案:

答案 0 :(得分:3)

代码退出getCurrentLocation方法后,您的位置管理器就会超出范围。建立一个位置管理员ivar,使其保持不变。

@interface AWSAppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
}



-(void)getCurrentLocation {
    locationManager = [[CLLocationManager alloc] init];
    // etc
}

答案 1 :(得分:1)

我修好了:D

我的locationManager对象 - 我实例化它,但你没有保留,所以它会在一阵烟雾中立即消失

@property (strong, nonatomic) CLLocationManager *locationManager;

然后,

-(void)getCurrentLocation {

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    self.locationManager.distanceFilter = 5;
    [self.locationManager startUpdatingLocation];
    NSLog(@"Started to get locations");
}

现在它完美无缺:D

答案 2 :(得分:0)

您的位置管理员是否已启用?检查一下:

if(locationManager.locationServicesEnabled == NO){
  //go to settings>location services
}

如果情况变坏,方法

locationManager:didFailWithError:
调用

而不是

locationManager:didUpdateLocations

所以,请执行它:

- (void)locationManager: (CLLocationManager *)manager didFailWithError: (NSError *)error {
    NSLog(@"error%@",error);
}