简体   繁体   中英

CLLocationManager not calling delegate in an NSObject

I'm trying to create a helper class to get the coordinates of the phone in any other class easily. I've followed a tutorial in which the UIViewController implemented the <CLLocationManagerDelegate> and it worked. I tried to do the same in a simple NSObject , but then my delegate was not called anymore.

This is the code I have :

PSCoordinates.h

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

@interface PSCoordinates : NSObject <CLLocationManagerDelegate>

@property (nonatomic, retain) CLLocationManager* locationManager;


@end

PSCoordinates.m

#import "PSCoordinates.h"

@implementation PSCoordinates

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

    if (self) {
        self.locationManager = [[CLLocationManager alloc] init];
        if ([CLLocationManager locationServicesEnabled])
        {
            self.locationManager.delegate = self;
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            self.locationManager.distanceFilter = 100.0f;
            NSLog(@"PSCoordinates init");
            [self.locationManager startUpdatingLocation];
        }
    }
    return self;
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"Géolocalisation : %@",[newLocation description]);
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    NSLog(@"Géolocalisation (erreur) : %@",[error description]);

}


@end

I'm calling it by calling

PSCoordinates * coordinates = [[PSCoordinates alloc] init];

when pressing a button. The init is working as I can see the NSLog PSCoordinates init .

I've found other topics of people having the same problem but none of the answer solved it.

Your help would be really appreciated.

Make "PSCoordinates * coordinates" as global in your class. It will work :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM