All Projects → Mindinventory → iOS-Geofence-Demo

Mindinventory / iOS-Geofence-Demo

Licence: MIT license
Setup Geofences and get notifications when the device enters or leaves the geofence.

Programming Languages

swift
15916 projects

Projects that are alternatives of or similar to iOS-Geofence-Demo

TET
TET- Trans Euro Trail - Public Files
Stars: ✭ 27 (-61.97%)
Mutual labels:  gpx
mealpy
Order your meals on MealPal automatically!
Stars: ✭ 28 (-60.56%)
Mutual labels:  restaurant
gpx-converter
python package for manipulating gpx files and easily converting gpx to other different formats
Stars: ✭ 54 (-23.94%)
Mutual labels:  gpx
GeoConvert
Converting between Geojson and GIS file formats
Stars: ✭ 32 (-54.93%)
Mutual labels:  gpx
NITKart
Shopping application on Android
Stars: ✭ 31 (-56.34%)
Mutual labels:  shopping
nrc-exporter
Download your runs data from Nike Run Club and convert it to GPX format that can be imported in other running apps.
Stars: ✭ 78 (+9.86%)
Mutual labels:  gpx
stravaV10
Open source bike GPS: with Strava segments !
Stars: ✭ 34 (-52.11%)
Mutual labels:  gpx
togeojson
convert KML, TCX, and GPX to GeoJSON, without the fuss
Stars: ✭ 315 (+343.66%)
Mutual labels:  gpx
wp-plugin-trackserver
A WordPress plugin for GPS tracking and publishing
Stars: ✭ 34 (-52.11%)
Mutual labels:  gpx
gc-gpx-viewer
Geocaching GPX Viewer is a web app to display caches from a gpx file on a map.
Stars: ✭ 24 (-66.2%)
Mutual labels:  gpx
GPXParser.js
GPX file parser javascript library
Stars: ✭ 58 (-18.31%)
Mutual labels:  gpx
Sistema-Restaurante
Open Source Software Restaurant
Stars: ✭ 61 (-14.08%)
Mutual labels:  restaurant
pentaho-gis-plugins
🗺 GIS plugins for Pentaho Data Integration
Stars: ✭ 42 (-40.85%)
Mutual labels:  gpx
garmin-connect-export
Downloads gpx, tcx or original fit files from your Garmin Connect Account.
Stars: ✭ 42 (-40.85%)
Mutual labels:  gpx
awesome-aizu
最高会津若松情報🍜🍣🍛🍝🌮🍜
Stars: ✭ 16 (-77.46%)
Mutual labels:  restaurant
GPS-Video-Logger
Android App to record video and track GPS data simultaneously. GPS Logger with Video. GPS and video recording.
Stars: ✭ 17 (-76.06%)
Mutual labels:  gpx
Strava-local-heatmap
Python script to generate a high resolution heatmap from Strava GPX files
Stars: ✭ 102 (+43.66%)
Mutual labels:  gpx
ezdmb
A dead-simple digital menu board display and configuration, written in Python.
Stars: ✭ 17 (-76.06%)
Mutual labels:  restaurant
React-Native-Shopping-App
A simple Shopping App in React Native. For Complete Functionality... check https://www.youtube.com/watch?v=Lf0MLrcSx0Q
Stars: ✭ 31 (-56.34%)
Mutual labels:  shopping
restaurant-bot
This is an Android application that can be used for providing a digital menu for a restaurant.
Stars: ✭ 42 (-40.85%)
Mutual labels:  restaurant

iOS Geofence Demo

You can setup your own geofence by providing latitude and longitude, and it will notify your app when the device enters or leaves the geofence.

Implementation of geofencing can be useful in various cases, You can define geofence that can trigger a notification whenever user enters or leaves the restaurant, Shopping center or particular region.

In this geofencing tutorial, you will learn how to use region monitoring in iOS with Swift 4.0 – using the Region Monitoring API in Core Location.

Requirements

Minimum OS 10.0 and later

Tip

  • To test in simulator you can use .GPX file (add GPX file file-> new -> under resource section there will option of GPX file)

  • For using GPX file when app is running in simulator there is option in xCode (debug -> simulate location -> select your GPX file)

  • In our demo we are using core data to store region data for testing perpose. our core data model looks like below:

    extension TblGeofence { 
       @nonobjc public class func fetchRequest() -> NSFetchRequest<TblGeofence> {
         return NSFetchRequest<TblGeofence>(entityName: "TblGeofence")
        }
    
     @NSManaged public var identifier: String?
     @NSManaged public var isFiredOn: Date?
     @NSManaged public var latitude: Double
     @NSManaged public var longitude: Double
     @NSManaged public var msg: String?
     @NSManaged public var range: Double
    @NSManaged public var title: String?
    
    }
    

Manual Installation

  1. First thing we need to do is setup Location manager and Location permissions.

    class AppDelegate: UIResponder, UIApplicationDelegate {  
    let locationManager = CLLocationManager()
    self.enableLocationServices()
     }
    
  2. Next we need to add Following methode in Appdelegate.

     func enableLocationServices() // to check status of locations
     {
     locationManager.delegate = self
     
     switch CLLocationManager.authorizationStatus() {
     case .notDetermined:
         // Request when-in-use authorization initially
         locationManager.requestAlwaysAuthorization()
         break
         
     case .restricted, .denied:
         print("status restricted, .denied \(CLLocationManager.authorizationStatus())")
         // Disable location features
         
         break
         
     case .authorizedWhenInUse:
         // Enable basic location features
         print("status authorizedWhenInUse \(CLLocationManager.authorizationStatus())")
         break
         
     case .authorizedAlways:
         print("status authorizedAlways \(CLLocationManager.authorizationStatus())")
         // Enable any of your app's location features
         
         break
     }
     
    }
    
  3. Now set the delegate of the locationManager instance so that we can receive callbacks to respective delegate methods.

     extension AppDelegate: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
        if region is CLCircularRegion {
         
         // Here region.identifier is identifier which you provide during register geofence region.
         // Now you can perform action you want to perfrom. that will same for below didExitRegion method
         
         let geoFance  = (TblGeofence.findOrCreate(dictionary: ["identifier":region.identifier]) as? TblGeofence)!
         if (!(geoFance.title?.isEmpty)!)
         {
             self.fireNotification(obj: geoFance,  isEnter: true)
         }
      }
     }
    
     func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
        if region is CLCircularRegion {
         
         let geoFance  = (TblGeofence.findOrCreate(dictionary: ["identifier":region.identifier]) as? TblGeofence)!
         if (!(geoFance.title?.isEmpty)!)
         {
             self.fireNotification(obj: geoFance,  isEnter: false)
         }
         
        }
      }
     }
    
  4. Registering Your Geofences with your location and radios of monitoring region

    func registerGeoFance(obj : TblGeofence) {
    
        if locationManager.monitoredRegions.count >= 20 // check current monitored region Apple allowed only 20 at time
        {
        locationManager.stopMonitoring(for: locationManager.monitoredRegions.first!) // if have to add new one then need to remove older then 20 else it will not add new one
         }
      let centerCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2DMake(obj.latitude, obj.longitude)
      let region = CLCircularRegion(center: centerCoordinate, radius: obj.range, identifier: obj.identifier!) // provide radius in meter. also provide uniq identifier for your region.
      region.notifyOnEntry = true // based on your requirements
      region.notifyOnExit = true
    
      locationManager.startMonitoring(for: region) // to star monitor region
      locationManager.requestState(for: region) // that will check if user is already inside location then it will fire  notification instantly.
     }
    
  5. To trigger notification when enter or leave a registered region, we can use Local Notifications using UNUserNotification framework which is supported only in iOS 10 or later versions

    func fireNotification(obj:TblGeofence , isEnter:Bool)
    
{
    
    print("notification will be triggered in five seconds..Hold on tight")
    let content = UNMutableNotificationContent()
    content.title = obj.title ?? "TitleMissing"
    content.subtitle = obj.msg! + "at lat = \(obj.latitude) long = \(obj.longitude)"
    content.body = "you are \(isEnter ? "enetr in" : "Exit from") \(obj.title ?? "TitleMissing")"
    content.sound = UNNotificationSound.default()
    
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.1, repeats: false)
    let request = UNNotificationRequest(identifier:obj.identifier! + "++ \(isEnter ? "1" : "0") \(NSDate.timeIntervalSinceReferenceDate)", content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().add(request){(error) in
        
        if (error != nil){
            
            print(error?.localizedDescription ?? "error in notifications")
        }
    }
}
  1. For perfom any action on notification we need to implement UNUserNotificationCenterDelegate

    extension AppDelegate:UNUserNotificationCenterDelegate{
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
     
     print("Tapped in notification")
     }
    
    //This is key callback to present notification while the app is in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
     
     print("Notification being triggered")
     let strDevides = notification.request.identifier.components(separatedBy: "++ ")
     
     let geoFance  = (TblGeofence.findOrCreate(dictionary: ["identifier":strDevides[0]]) as? TblGeofence)!
     
     DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(0))) {
                     let alert = UIAlertController(
                         title: "\(geoFance.title ?? "BlankTitleRecevied")",
                         message: "\(notification.request.content.subtitle) \n \(notification.request.content.body)",
                         preferredStyle: UIAlertControllerStyle.alert
                     )
         
                     alert.addAction(UIAlertAction(title: "Okey", style: .cancel, handler: { (alert) -> Void in
                         
                     }))
         
                     UIApplication.topViewController()?.present(alert, animated: true, completion: nil)
         
                 }
     
     //You can either present alert ,sound or increase badge while the app is in foreground too with ios 10
     //to distinguish between notifications
     if notification.request.identifier == "123456"{
         
         completionHandler( [.alert,.sound,.badge])
         
       }
     }
    
    }
    
  2. Now we have created one ViewController where we can add our geofence region.

    • Drag and Drop ViewControlle.swift file in your Projects.

LICENSE!

Geofence is MIT-licensed.

Let us know!

We’d be really happy if you send us links to your projects where you use our component. Just send an email to [email protected] And do let us know if you have any questions or suggestion regarding our work.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].