locationManager无法在iOS 9

时间:2015-09-03 12:18:55

标签: ios objective-c iphone

我的GPS位置刷新信息有问题。 单击按钮时由我“locationManager”给出的功能不会刷新“标签”中的信息。

我的代码:http://pastebin.com/hWeq6gTS

我是iOS的新手程序员。请帮忙。

4 个答案:

答案 0 :(得分:6)

位置服务并不总是显而易见的问题是,您必须在Info.plist中使用这两个密钥中的一个:

  1. NSLocationWhenInUseUsageDescription
  2. NSLocationAlwaysUsageDescription
  3. 然后,在开始更新您的头寸时,不要忘记首先请求权限(再次,根据您的要求(在使用/总是)时:

    1. [self.locationManager requestWhenInUseAuthorization]
    2. [self.locationManager requestAlwaysAuthorization]

答案 1 :(得分:4)

在info.plist中添加这两个属性

' NSLocationAlwaysUsageDescription'及以下财产

enter image description here

创建CocoaTouch类' LocationManager'像下面的类一样从NSObject继承。

Singleton Location Manager Class .h

#import <Foundation/Foundation.h>

@interface LocationManager : NSObject <CLLocationManagerDelegate>
{
    CLLocationManager *locationManager;
}

@property (strong, nonatomic) NSString *longitude;
@property (strong, nonatomic) NSString *latitude;
@property (strong, nonatomic) CLLocation *currentLocation;

+ (instancetype)sharedInstance;

@end

在这里实施.m

#import "LocationManager.h"

@implementation LocationManager

- (id) init
{
    self = [super init];

    if (self != nil)
    {
        [self locationManager];
    }
    return self;
}


+ (instancetype)sharedInstance
{
    static LocationManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[LocationManager alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

- (void) locationManager
{
    if ([CLLocationManager locationServicesEnabled])
    {
        locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        locationManager.distanceFilter = kCLDistanceFilterNone;
        if ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
        {
            [locationManager requestWhenInUseAuthorization];
        }
        [locationManager startUpdatingLocation];
    }
    else{

        UIAlertView *servicesDisabledAlert = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled" message:@"You currently have all location services for this device disabled. If you proceed, you will be showing past informations. To enable, Settings->Location->location services->on" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:@"Continue",nil];
        [servicesDisabledAlert show];
        [servicesDisabledAlert setDelegate:self];
    }
}

- (void)requestWhenInUseAuthorization
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    // If the status is denied or only granted for when in use, display an alert
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
        NSString *title;
        title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" : @"Background location is not enabled";
        NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";

        UIAlertView *alertViews = [[UIAlertView alloc] initWithTitle:title
                                                             message:message
                                                            delegate:self
                                                   cancelButtonTitle:@"Cancel"
                                                   otherButtonTitles:@"Settings", nil];
        [alertViews show];
    }
    // The user has not enabled any location services. Request background authorization.
    else if (status == kCLAuthorizationStatusNotDetermined) {
        [locationManager requestWhenInUseAuthorization];
    }
}


#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", error);
    UIAlertView *errorAlert = [[UIAlertView alloc]
                               initWithTitle:@"Error" message:@"Failed to Get Your Location" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//    [errorAlert show];
}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
        case kCLAuthorizationStatusRestricted:
        case kCLAuthorizationStatusDenied:
        {
            // do some error handling
        }
            break;
        default:{
            [locationManager startUpdatingLocation];
        }
            break;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

    CLLocation *location;
    location =  [manager location];
    CLLocationCoordinate2D coordinate = [location coordinate];
    _currentLocation = [[CLLocation alloc] init];
    _currentLocation = newLocation;
    _longitude = [NSString stringWithFormat:@"%f",coordinate.longitude];
    _latitude = [NSString stringWithFormat:@"%f",coordinate.latitude];
    //    globalObjects.longitude = [NSString stringWithFormat:@"%f",coordinate.longitude];
    //    globalObjects.latitude = [NSString stringWithFormat:@"%f",coordinate.latitude];
}


@end

导入

#import "LocationManager.h"

在AppDelegate.h中

并在你的AppDelegate.m中调用它

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [LocationManager sharedInstance];
    return true;
}

然后得到 [LocationManager sharedInstance]。更新lat long的.longitude或纬度。

答案 2 :(得分:3)

而不是使用

-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation:(CLLocation *)newLocation
          fromLocation:(CLLocation *)oldLocation{
 // Location update code
} 

使用此功能获取更新位置

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
           // Assigning the last object as the current location of the device
           CLLocation *currentLocation = [locations lastObject];

 }

答案 3 :(得分:0)

当我们不检查授权状态时,有时我们会遇到问题。您可以查看此代码

        // Custom initialization code
    CLLocationManager *manager = [[CLLocationManager alloc]init];
    manager.delegate = self;
    manager.desiredAccuracy = kCLLocationAccuracyBest;
    // Setting distance fiter to 10 to get notified only after location change about 10 meter
    manager.distanceFilter = kCLDistanceFilterNone;

    // Requesting for authorization

    if ([manager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
        [manager requestWhenInUseAuthorization];
    }

    // Immediately starts updating the location
    [manager startUpdatingLocation];
    [manager startUpdatingHeading];

如果__IPHONE_OS_VERSION_MAX_ALLOWED&gt; = 80000

    // user activated automatic attraction info mode
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusDenied ||
        status == kCLAuthorizationStatusAuthorizedWhenInUse ||
        status == kCLAuthorizationStatusNotDetermined) {
        // present an alert indicating location authorization required
        // and offer to take the user to Settings for the app via
        // UIApplication -openUrl: and UIApplicationOpenSettingsURLString
        [manager requestAlwaysAuthorization];
    }

    [manager requestWhenInUseAuthorization];

否则

    [manager requestAlwaysAuthorization];

ENDIF