Search code examples
iosswiftibeacongeofencing

ibeacons and geofencing combined swift


I am using both geofencing and beacons in my swift project. But their entered and exit method clash everytime I enter or leave any of the region. To be more specific, how can I execute different method to corresponding beacon or geofence region ??e.g. I want to show a notification when the user enters the geofence region and display other page when it enters the beacon region.


Solution

  • Geofence regions and beacon regions are both regions, so the same didEnterRegion method is called to notify you about both. You need to write your didEnterRegion method to check the class of the region with an if statement. (I forget the syntax for that in Swift.)

    EDIT:

    The Objective-C code would be

    if ([region isMemeberOfClass: [CLBeaconRegion class]])
    {
      //beacon code
    }
    else
    {
      //geofence code
    }
    

    You could certainly convert that to Swift syntax, but David Young showed the better way in his comment, below:

    if let beaconRegion = region as? CLBeaconRegion
    {
      //beacon code
    }
    else
    {
      //geofence code
    }
    

    (Thanks David. Answering technical questions from my iPad, before I've had coffee, is only of limited use.)