在iOS应用的多个视图中重复调用geolocation单例类



在阅读了一些关于堆栈溢出的建议和其他一些文章之后,我实现了一个单例类,它允许我调用一个方法来更新用户的当前位置。为了避免位置信息的持续更新,我添加了一个StopUpdatingPosition调用。第一次可以正常工作,但是接下来的调用会失败。

我相信这是因为在提供的示例中启动地理定位的方式,它检查单例是否已经到位(?)

如果一个单例被初始化,它是否保留在内存中?在随后的呼叫,我可以检查,看看如果这是这种情况下,只是要求它开始更新位置?

这是我到目前为止尝试过的。

- (id)init {
    self = [super init];
    if(self) {
        self.locationManager = [CLLocationManager new];
        [self.locationManager setDelegate:self];
        [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
        [self.locationManager setHeadingFilter:kCLHeadingFilterNone];
        [self.locationManager startUpdatingLocation];
        geocoder = [[CLGeocoder alloc] init];
    }
    return self;
}
+ (LocationFunction*)sharedSingleton {
    static LocationFunction* sharedSingleton;
    if(!sharedSingleton) {
        @synchronized(sharedSingleton) {
            sharedSingleton = [LocationFunction new];
        }
    }
    return sharedSingleton;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"didUpdateToLocation: %@", newLocation);
    CLLocation *currentLocation = newLocation;
    if (currentLocation != nil) {
        myLat = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
        myLong = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.longitude];
    }
    // Store the Long & Lat to global variables here
    NSLog(@"Resolving the Address");

        } else {
    // Handle location lookup fail here
        }
    } ];
    [manager stopUpdatingLocation];
    }

我正在寻找一种在不同视图控制器的外部类中调用方法的方法。这个方法获取用户的当前位置(Long &Lat),将信息记录在一个全局变量中,停止任何更新location方法的请求,并在完成时通知视图控制器。

指针感激。

另一个stackoverflow问题的答案提供了一个解决方案。然而请注意,调用是不正确的(我无法评论答案-太新stackoverflow!)。它应该引用"sharedManager":

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[MyClass sharedManager] startCapture];
}

最新更新