user6438311 user6438311 - 1 month ago 12
Objective-C Question

How to get Notification when region Changes of the user?

I am working on application in which I have to use region monitoring.
When the location of user changes according to that the user will get notification about the location that user now is in the new location, Even when the application is in background.


I am trying from the last few days and searched in the Google but I am not finding the solution or any idea that how to do.
Is here anyone who can help me?

Thanks in advance.

Answer

Use geofencing with the help of CLLocationManager and call the startMonitoringForRegion

Make a function like this and start monitoring for region

-(void)notificationForRegion:(CLLocationDegrees) latitude withLongitude:(CLLocationDegrees) longitude andIdentifier : (NSString*) identifer {
    CLLocationManager * locationManager = [[CLLocationManager alloc] init];
    CLCircularRegion * regionForMonitoring = [[CLCircularRegion alloc] initWithCenter:CLLocationCoordinate2DMake(latitude, longitude) radius:50.0 identifier:identifer];
    regionForMonitoring.notifyOnExit = TRUE;
    [locationManager startMonitoringForRegion:regionForMonitoring];
}

Implement didEnterRegion delegate method of CLLocationManagerDelegate in AppDelegate as AppDelegate object remains in memory always and schedule your local notifications here.

-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
    UILocalNotification * localNotif = [[UILocalNotification alloc] init];
    localNotif.alertBody = @"You are now in the region";
    localNotif.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
    localNotif.soundName = UILocalNotificationDefaultSoundName;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [manager stopMonitoringForRegion:region];  
}

Call the above notificationForRegion function as follows

After getting your location

[self notificationForRegion:location.coordinate.latitude withLongitude:location.coordinate.longitude andIdentifier:@"your identifier"];