Ganpati
How to integrate Geofencing in an iOS App?

How to integrate Geofencing in an iOS App?

30 July, 2020 by img Bhavesh Nayi in iOS App Development
How to integrate Geofencing in an iOS App?

What is a Geofence?

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.

 

Applications of Geofencing in Mobile Development

Geofencing can be used several applications such as:

  • Marketing: a clothing store can trigger a push notification with the day’s offers and discounts when a customer is nearby.
  • Reminders: an app that reminds the fans of a football club the address of the gates they should go to enter the stadium while they are in the surroundings.
  • Arrivals and departures from a certain location: an airline can send a notification wishing the user a safe trip after the plane has taken off or a welcome message when the plane has landed.
  • Child Tracking: an app can send a notification telling a parent that his child has left or entered a certain area.
  • Security: the app can enable or disable features when entering or leaving a region.

 

Advantages Of Geofencing App

  • Customer engagement by providing real time offers, discounts and promotions.
  • Enhance user experience.
  • Send location specific notifications to users.

 

Disadvantages of Geofencing

  • Geofencing requires the approval of the user. If the user rejects or disables the location services, geofencing won’t work until enabled from the app settings.
  • Location tracking takes too much battery life and this is the first cause for users turning off location services in the device.
  • Only appropriate for wide range areas.

 

How to integration in iOS app?

 

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

 

Geofencing

 

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 in AppDelegate
import CoreLocation
  • Create Global variable for Location and Geofence
var locationManager : CLLocationManager!     //FOR LOCATION
var geofenceRegion = CLCircularRegion()          //FOR GEOFENCE

  • Implement Location service in “didFinishLaunchingWithOptions” in AppDelegate
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)

        }

    }


–  Added Location delegate Method


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))")

       }
}

–  Schedule Local Notification


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!) {

}

 

How Rlogical Techsoft helps for develops Geofencing App?

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.

Contact us with your requirements for development of Geofencing apps in iOS.

 

References:

https://medium.com/academyufpe/geofencing-in-ios-swift-for-noobs-29a1c6d15dcc

https://www.raywenderlich.com/5470-geofencing-with-core-location-getting-started

img

Bhavesh Nayi

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.

Get in Touch

Contact Us

    Input Captcha Here: captcha

    sprite_image.png?v=1714061534USA

    3728 N Fratney St Suite 213, Milwaukee, WI 53212, United States

    Sales Executive: +1 414 253 3132

    Contact Email: [email protected]

    sprite_image.png?v=1714061534UK

    5 Kew Road, TW9 2PR, London

    Contact Email: [email protected]

    sprite_image.png?v=1714061534 INDIA (Head Office)

    701 & 801 Satkar Complex, Opp Tanishq Showroom,Behind Lal Bungalow, Chimanlal Girdharlal Rd, Ahmedabad, Gujarat 380009

    Rahul Panchal: +91-9824601707
    Jatin Panchal: +91-9974202036

    Contact Email: [email protected]

    sprite_image.png?v=1714061534 JAPAN

    301 1-28-21 Hayabuchi, Tsuzuki-ku, Yokohama-shi, Kanagawa 224-0025, Japan

    Contact Email: [email protected]

    sprite_image.png?v=1714061534 Australia

    Suit 3, Level 27, 1 Farrer Place Sydney NSW 2000

    Contact Email: [email protected]