0

我正在使用单例类来跟踪用户位置。如果我从正在运行的应用程序中实例化该类并开始跟踪一切都很好。

但是,如果应用程序关闭(在应用程序切换器中,因此不再后台运行)并重新启动,我会检查是否有活动事件。在这种情况下,我实例化类并开始位置跟踪。被locationManager实例化并且位置箭头出现在状态栏中,但是

    -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations 
or 
    -(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
never get called

任何想法?

代码singelton类:

@interface AlarmMeTrackUserLocation () <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@end

@implementation AlarmMeTrackUserLocation    
-(void)toggleLocationUpdates:(bool)toggle {

    if (!toggle) {
        [self.locationManager stopUpdatingLocation];
        self.locationManager = nil;
        sharedInstance = nil;
        NSLog(@"--- UserTrack Stopped ---");
        return;
    }


    if (!self.locationManager && toggle) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        self.locationManager.pausesLocationUpdatesAutomatically = YES;
        self.locationManager.distanceFilter = 200;
    }

    NSLog(@"--- UserTrack Started");
    [self.locationManager startUpdatingLocation];

}

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

- (void)locationManager:(CLLocationManager *)manager
   didFailWithError:(NSError *)error {
    ...
}

+ (AlarmMeTrackUserLocation *)sharedTrackUserLocation {

    if (sharedInstance == nil) {
        sharedInstance = [[super allocWithZone:NULL] init];

        //NSLog(@"--- New Instance created ---");

        return sharedInstance;
    }

    NSLog(@"--- Existing Instance Used ---");

    return sharedInstance;
}

来自 AppDelegate 的代码:

@property (strong, nonatomic) AlarmMeTrackUserLocation *userTrack;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ...
    self.userTrack = [AlarmMeTrackUserLocation sharedTrackUserLocation];
    self.userTrack.event = currentEvent;
    [self.userTrack toggleLocationUpdates:YES];

}
4

1 回答 1

0

在仔细查看我的代码后,我只能看到一个区别:在应用程序委托中,我启动了一个后台线程来从网络服务器获取数据。如果请求完成,则实例化单例类并设置 locationManager(仍在后台线程中)。

切换回主线程并实例化它终于可以工作了!

所以看起来你不能从后台线程委托 CLLocationManager

于 2013-05-06T21:15:24.147 回答