didEnterRegion works in foreground but not background or other VCs

限于喜欢 提交于 2019-11-29 02:19:19

A friend of mine wrote up a nice tutorial on using geofencing that might help clear up some issues you are having.

Get started with geofencing

There are plenty of examples online and here on SO. Start out small and work your way up. Once you start getting your callbacks, you can start expanding things out to your other view controllers.

UPDATE

As explained in the comments the benefits of creating a singleton class to control your location manager and delegate methods. By using a singleton, you prevent the possibility of getting multiple calls to your delegate methods. You can prevent this by careful coding, but using a singleton does this for you. This is also a nice class to handle all the work needing to be done by your delegate methods.

Things you are doing wrong:

  1. Background modes - App registers for location updates. This is not needed. This is need when you want to gather info for significant changes in location etc. So, go to Targets > Your app > Capabilites , and select the desired option under Background modes. This will automatically update the plist for you. For now, disable it.
  2. You are trying to create an alert when the user enters a region. While this while work when app is working, an alert is of no use when your app is in background. Do - Rather trigger a local notification or an api call.

eg. of a notification:

    -(void)triggerLocalNotification:(CLRegion *)region{
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    [notification setAlertBody:[NSString stringWithFormat:@"Welcome to %@", [region identifier]]];
    [notification setRepeatInterval:0];
    [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:2]];
    [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
    [[UIApplication sharedApplication]scheduleLocalNotification:notification];
    NSLog(@"notification triggered with notification %@", notification);
}

You can post a local notification when you didEnterRegion.

This will show an alert-like popup even if you're in the background.

You can do a simple test:

1) Create a Local notification object inside your applicationDidEnterBackground of your app delegate, with any random message and tell the local notification to fire immediately.

2) Press the home button, when you app minimise, you should see a popup.

i think you need go to your app.plist

and add Required Background modes : add itme App registers for location update

and 1 . if you app is in background , you still see the arrow on top

and 2 , if the app killed , you can still see a hollow arrow on the top , ios will monitor the region for you , but limited to 20 regions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!