【问题标题】:How do I persist CLLocation between app launches?如何在应用启动之间保持 CLLocation?
【发布时间】:2011-04-03 12:34:36
【问题描述】:
我想在应用启动之间保留 2 个 CLLocations。这是我希望在两次启动之间存储在内存中的唯一数据。我该怎么做呢? CLLocation 是否有 writetofile 或将其存储在 coredata 或 NSUserDefaults 中?我想存储整个 CLLocation 对象,不想只存储纬度/经度然后进行更多计算等。谢谢
【问题讨论】:
标签:
iphone
objective-c
ios
【解决方案1】:
查看文档,我看到CLLocation 实现了NSCoding 协议。
这意味着您可以使用NSKeyedArchiver 和NSKeyedUnarchiver 类归档和取消归档CLLocation 实例。
您还可以将CLLocation 的多个实例放在实现NSCoder 的任何容器(父)类中,例如NSDictionary 或NSArray,然后归档或取消归档整个对象集合。
有关更多详细信息,请参阅Archives and Serializations Programming Guide。或者,如果您遇到困难,请使用代码发布后续问题。
【解决方案2】:
St3fan 的回答让我觉得物有所值,而且效果很好。简单问题的简单解决方案!我想我会分享我想出的代码。
我有一个 Singleton 类来保存我的 CLLocationManager,这个类处理持久性并将 CLLocationManagerDelegate 方法转发给一个委托数组,以防多个类对这些消息感兴趣(我的一直都是这种情况)应用程序)。
此代码可能无法用作复制/粘贴工作,但如果您无法从中找出您需要什么,请查找单例模式并学习它! _lastLocation 是一个具有只读属性的 ivar,供其他类读取。 persistLastLocation 负责保存位置。您应该在获得新位置时调用它。
///////////////////////////////////////// /////////////////////////////////////////
- (id)初始化{
self = [超级初始化];
如果(自我){
self.myLocationManager = [[CLLocationManager alloc] init];
self.myLocationManager.delegate = self;
// 一些配置
self.myLocationManager.desiredAccuracy = 482; // 0.3 英里
self.myLocationManager.distanceFilter = 200;
NSLog(@"CLLocationManager authStatus on start up: %d", [CLLocationManager authorizationStatus]);
NSLog(@"位置服务启用:%d", [CLLocationManager locationServicesEnabled]);
CLLocation *decodedLocation = [NSKeyedUnarchiver unarchiveObjectWithFile:[self lastLocationPersistenceFilePath]];
如果(解码位置){
NSLog(@"解码位置:%@", decodedLocation);
_lastLocation = 解码位置;
}
}
回归自我;
}
#pragma 标记 -
#pragma 标记 MyLocationManager
///////////////////////////////////////// /////////////////////////////////////////
- (NSString *)lastLocationPersistenceFilePath {
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"my_app_last_location"];
返回文件路径;
}
///////////////////////////////////////// /////////////////////////////////////////
- (void)persistLastLocation {
BOOL 成功 = [NSKeyedArchiver archiveRootObject:self.lastLocation
toFile:[self lastLocationPersistenceFilePath]];
如果(!成功){
NSLog(@"由于某种原因无法保存位置!");
}
}
#pragma 标记 -
#pragma 标记 CLLocationManagerDelegate
///////////////////////////////////////// /////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
// 将此消息转发到新的 iOS 6 委托方法。
[self locationManager:manager didUpdateLocations:@[oldLocation]];
}
///////////////////////////////////////// /////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *latestLocation = [位置 lastObject];
_lastLocation = 最新位置;
[自我坚持上一个位置];
}