MBLocationManager
位置管理器提供方便且易于使用的最新 iOS 设备位置访问。它使用便利的单例类包装 CoreLocation,让您无需保留位置管理器对象的引用。
主要特性
- 用 3 行代码订阅位置更新
- 三种操作模式:只有在应用使用时跟踪用户的位置(仅限 iOS 8)、即使在后台也跟踪位置或仅跟踪重大位置变化
- 使用 CoreLocation 的距离过滤器和精度模式
- 当应用进入后台或前台时,轻松暂停和恢复
- 一次性实例化位置管理器,通过订阅通知在需要的地方使用
集成 iOS 7 和新的 iOS 8 CoreLocation API。
现在也完全经过单元测试。
安装
应通过 Cocoa Pods 进行安装。
如果尚未安装,安装 CocoaPods
sudo gem install cocoapods
pod setup
切换到您的 Xcode 项目的目录,创建并编辑您的 Podfile
并添加以下行
pod 'MBLocationManager'
pod install
在 Xcode 中从 .xcworkspace 文件(而不是通常的项目文件)打开您的项目
使用
1. 添加必要的.plist条目
从iOS 8开始,您必须定义一个将在位置授权请求中显示给用户的消息。您需要将此消息定义为应用中的*-Info.plist文件。您需要添加以下至少一项键,具体取决于请求的位置更新模式
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
请确保您已将该键添加到正确的.plist文件(常见错误是将它添加到test-Info.plist)。也不要将实际的消息文本作为值添加。 如果未将键添加到 plist 文件,将阻止您的应用请求用户权限,从而使位置更新无效。
2. 开始追踪位置
为了在设备上开始追踪位置,请在AppDelegate.h中的application:didFinishLaunchingWithOptions
方法中调用startLocationUpdates:distanceFilter:accuracy
方法。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[MBLocationManager sharedManager] startLocationUpdates:kMBLocationManagerModeStandardWhenInUse
distanceFilter:kCLDistanceFilterNone
accuracy:kCLLocationAccuracyThreeKilometers];
return YES;
}
3. 订阅通知事件
从您打算使用设备位置的viewcontroller中,订阅通知kMBLocationManagerNotificationLocationUpdatedName
,该通知在检测到新位置时触发。当发布通知时,可访问MBLocationManager的currentLocation
属性。
通知kMBLocationManagerNotificationFailedName
会通知您有关确定位置的失败尝试(请参阅locationManager:didFailWithError)
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(changeLocation:)
name:kMBLocationManagerNotificationLocationUpdatedName
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(locationManagerFailed:)
name:kMBLocationManagerNotificationFailedName
object:nil];
}
-(void)locationManagerFailed:(NSNotification*)notification
{
NSLog(@"Location manager failed");
}
-(void)changeLocation:(NSNotification*)notification
{
CLLocation *location = [[MBLocationManager sharedManager] currentLocation];
NSLog(@"Location changed to %@", self.locationLabel.text);
}
4. (可选)在后台时暂停位置更新
为了提高电池寿命,您可能希望在进入后台时阻止应用跟踪位置变化。
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[[MBLocationManager sharedManager] stopLocationUpdates];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[MBLocationManager sharedManager] startLocationUpdates];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
[[MBLocationManager sharedManager] stopLocationUpdates];
}
精确调整CoreLocation设置
通过访问 locationManager
属性,您可以精确调整CoreLocation设置,例如 activityType
和 pausesLocationUpdatesAutomatically
。