在我的项目设置中>目标>功能我通过选中“位置更新”来启用背景模式。
的AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.storyController = [StoryController sharedController];
self.storyController.locationManager.delegate = self;
... etc initializing VC ...
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
NSLog(@"entered region, %@", region.identifier);
[self handleRegionEvent:region];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
NSLog(@"exited region, %@", region.identifier);
[self handleRegionEvent:region];
}
- (void)handleRegionEvent:(CLRegion *)region {
NSLog(@"handle region");
if ([UIApplication sharedApplication].applicationState ==
UIApplicationStateActive) {
NSLog(@"handle region local");
UILocalNotification *n = [[UILocalNotification alloc] init];
n.alertBody = @"LOCAL";
n.soundName = @"Default"; //Coffee Man?
[[UIApplication sharedApplication] presentLocalNotificationNow:n];
} else {
if ([[StoryController sharedController] readyForNextChapter]) {
UILocalNotification *n = [[UILocalNotification alloc] init];
n.alertBody = @"New ☕ Story";
n.soundName = @"Default"; //Coffee Man?
[[UIApplication sharedApplication] presentLocalNotificationNow:n];
}
}
}
StoryController
+ (id)sharedController {
static StoryController *myController = nil;
static dispatch_once_t token;
dispatch_once(&token, ^{
myController = [[StoryController alloc] init];
});
return myController;
}
- (id)init {
self = [super init];
self.locationManager = [[CLLocationManager alloc] init];
NSLog(@"monitored regions: %@", self.locationManager.monitoredRegions);
我稍后会对该地区进行监控:
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:g.coordinate radius:1000 identifier:"My Store"];
region.notifyOnEntry = true;
region.notifyOnExit = true;
NSLog(@"%d", [CLLocationManager authorizationStatus]);
[[[StoryController sharedController] locationManager] startMonitoringForRegion:region];
当我离开或进入1公里范围时,我没有收到任何通知,应用程序背景。
如何使这项工作?当我退出监控区域时,我确实看到了lat& lng是对的。
答案 0 :(得分:1)
确保您正在做的事情需要做两件事。
检查区域监控的可用性
确保您的locationManager.authorizationStatus ==。unauthorizedAlways
有些系统根本不支持区域监控,区域监控永远不会工作,除非你的authorizationStatus是。从授权开始,只有这样才能在后台进行监控。