A Geo-fence is a feature that defines a virtual boundary around a real world geographical area. Every time the user enters or exits the boundary of a certain area, actions can be triggered in a location enabled device. Usually the user will receive a notification with certain information based on its location in real time.
The main advantage of this technology is that it creates a fusion between the virtual world and the real one. At Lateral View we make use of Geofencing in several projects, particularly in the health industry.
Geofencing notifies your app when its device enters or leaves geographical regions you set up. It lets you make cool apps that can trigger a notification whenever you leave home, or greet users with the latest and greatest deals whenever favorite shops are nearby.
In this geofencing tutorial, you’ll learn how to use region monitoring in iOS with Swift – using the Region Monitoring API from Core Location.
Geofencing can be used several applications such as:
1) In order to work with geofences we need to import CoreLocation framework.
2) Please add ‘Background Modes’ in signing & compatibility and enable location service . Like below image
3) Add below key in Info.plist files
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Allow location access for geofencing goodness</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Allow location access for geofencing goodness</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Allow location access for geofencing goodness</string>
After that, We define a locationManager in our Appdelegate and we make the Appdelegate a CLLocationManagerDelegate:
import CoreLocation
var locationManager : CLLocationManager! //FOR LOCATION var geofenceRegion = CLCircularRegion() //FOR GEOFENCE
class AppDelegate: UIResponder, UIApplicationDelegate { var locationManager: CLLocationManager? var notificationCenter: UNUserNotificationCenter? var geofenceRegion = CLCircularRegion() //FOR GEOFENCE func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // step 1 self.locationManager = CLLocationManager() self.locationManager!.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; self.locationManager.distanceFilter = kCLDistanceFilterNone; self.locationManager.requestAlwaysAuthorization() self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() // get the singleton object self.notificationCenter = UNUserNotificationCenter.current() // register as it's delegate notificationCenter.delegate = self // define what do you need permission to use let options: UNAuthorizationOptions = [.alert, .sound] // request permission notificationCenter.requestAuthorization(options: options) { (granted, error) in if !granted { print("Permission not granted") } } //SET REGION AND SET GEOFENCE self.setRegionListAndGeoFencing() return true } } Setup Region and setup Geofence func setRegionListAndGeoFencing() { //Fillup Region List (Add Latitude and Longitude for perticular region), You can set manually or dynamic value for region regionList.add("23.0413432,72.5672913") //INCOMETAX, Ahmedabad regionList.add("51.5919139,-0.4031427") //Harrow, UK regionList.add("3.157917,101.7075007") //Petronas Twin Towers, Malaysia regionList.add("-33.8386865,151.0493946") //Sydney Olympic Park, Sydney, Austrlia regionList.add("37.7531667,-122.4939421") //Golden Gate Park, San Francisco, CA, USA //SET GEOFENCE FOR ABOVE REGION self.generateGeofenceRegion() } //MARK:- For Geofencing func generateGeofenceRegion() { geofenceRegion.notifyOnExit = true; geofenceRegion.notifyOnEntry = true; for i in 0..<regionList.count { let region = regionList.object(at: i) as! String let regionArr = region.components(separatedBy: ",") let lat = (regionArr[0] as NSString).doubleValue let long = (regionArr[1] as NSString).doubleValue let cellradius = 500 let geofenceRegionCenter = CLLocationCoordinate2DMake(lat, long); geofenceRegion = CLCircularRegion( center: geofenceRegionCenter, radius: CLLocationDistance(cellradius), identifier:region ); geofenceRegion.notifyOnExit = true; geofenceRegion.notifyOnEntry = true; self.locationManager.startMonitoring(for: geofenceRegion) } }
extension AppDelegate: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { if region is CLCircularRegion { // Do what you want if this information self.handleEventForExitRegion(forRegion: region) } } // called when user Enters a monitored region func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { if region is CLCircularRegion { // Do what you want if this information self.handleEventForEnterRegion(forRegion: region) } } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { print("didChangeAuthorization") print(CLLocationManager.authorizationStatus()) } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { let locValue = manager.location!.coordinate print("locations = \(locValue.latitude) \(locValue.longitude)") } func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) { print("update failure \(String(describing: error))") } }
func handleEventForEnterRegion(forRegion region: CLRegion!) { // customize your notification content let content = UNMutableNotificationContent() content.title = "Awesome title" content.body = "Well-crafted body message" content.sound = UNNotificationSound.default() // when the notification will be triggered var timeInSeconds: TimeInterval = (60 * 15) // 60s * 15 = 15min // the actual trigger object let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInSeconds, repeats: false) // notification unique identifier, for this example, same as the region to avoid duplicate notifications let identifier = region.identifier // the notification request object let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) // trying to add the notification request to notification center notificationCenter.add(request, withCompletionHandler: { (error) in if error != nil { print("Error adding notification with identifier: \(identifier)") } }) } func handleEventForExitRegion(forRegion region: CLRegion!) { }
Rlogical Techsoft is a leading IT company known for web & mobile app development in India. We have expertise in providing app solutions based on Geolocation leveraging Geolocation based mobile app development and solutions.
https://medium.com/academyufpe/geofencing-in-ios-swift-for-noobs-29a1c6d15dcc
https://www.raywenderlich.com/5470-geofencing-with-core-location-getting-started
He is a Sr. iOS Developer at Rlogical Techsoft. He is hardworking and dedicated person, love to explore, always have a big hunger for new knowledge. He is passionate about iOS and expert in building an innovative iOS mobile application.