gpt4 book ai didi

iOS CLLocationManager 在一个单独的类中

转载 作者:IT王子 更新时间:2023-10-29 08:17:09 25 4
gpt4 key购买 nike

我有多个 View Controller 需要获取用户的位置,所以我想创建一个单独的类,ViewController 可以调用它来获取用户的最新位置。

locationManager:didUpdateToLocation:fromLocation 返回无效。如何在计算出用户的纬度和经度后立即将纬度和经度数据传回我的 ViewController?

我可以尝试在我的 locationManaging 类中编写 getter 和 setter,但如果这样做,我如何知道何时从我的 ViewController 类中调用纬度 getter 和经度 getter 方法?如何让 ViewController 的主线程等待来自 locationManaging 类的纬度和经度值?

谢谢!

最佳答案

正如 user1071136 所说,单例位置管理器可能就是您想要的。创建一个类,它是 NSObject 的一个子类,只有一个属性,一个 CLLocationManager

LocationManagerSingleton.h:

#import <MapKit/MapKit.h>

@interface LocationManagerSingleton : NSObject <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager* locationManager;

+ (LocationManagerSingleton*)sharedSingleton;

@end

LocationManagerSingleton.m:

#import "LocationManagerSingleton.h"

@implementation LocationManagerSingleton

@synthesize locationManager;

- (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];
//do any more customization to your location manager
}

return self;
}

+ (LocationManagerSingleton*)sharedSingleton {
static LocationManagerSingleton* sharedSingleton;
if(!sharedSingleton) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedSingleton = [LocationManagerSingleton new];
}
}

return sharedSingleton;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
//handle your location updates here
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
//handle your heading updates here- I would suggest only handling the nth update, because they
//come in fast and furious and it takes a lot of processing power to handle all of them
}

@end

要获取最近收到的位置,只需使用 [LocationManagerSingleton sharedSingleton].locationManager.location。预热 GPS 以获得准确位置可能需要几秒钟。

关于iOS CLLocationManager 在一个单独的类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11513259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com