How To Create A Geofence For Your Mobile App – Swift
This guide is for adding geofences to your iOS app, using Swift with the SpotSense SDK. It is current as of May 4th, 2020.
What you’ll need
- Xcode (free)
- Apple developer account (free)
- Your own iOS app written in Swift (Or you can download a sample app here)
- SpotSense account (free)
1) Create an Apple Developer account
https://developer.apple.com > Account > Create account
2) Download the latest version of Xcode from iTunes
- https://developer.apple.com/xcode/ > Download
3) Download sample app from Github (If you don’t have your own mobile app)
- This is a mobile app that connects to Firebase and lists points of interest in a given city
4) SpotSense SDK setup
- https://www.spotsense.io > Dashboard
- Click sign in or create account
- Under “Add an app” Choose iOS via Cocoapods
- Name your mobile app > List the bundle ID you’re using for your mobile app
- Install the SpotSense podfile (Cocoapods will generate a
.xcworkspacefile. Be sure to use this file when developing your application)
- In your
ViewController.swift, initialize SpotSense with your app’s client id and secret.
- Add delegates to ViewController and initialize
- Add the SpotSense initialization code to
ruleDidTriggermethod to ViewController
- Add locationManager delegate to notify SpotSense of geofence events
didStartMonitoringFormethod for debugging geofences (optional)
5) Create your geofence
- On SpotSense dashboard, click geofence > Create my first geofence
- Name your geofence
- Draw geofence on map where you want to track enter and exit events
- Type notification text in notification section
- Click create
6) Set up your mobile app on your device
- Plug your iPhone into your machine
- In Xcode, select the dropdown in the top left corner next to your app name > Choose your device
- Run the app (This should start running the application on your phone)
Go test the geofence!
There’s two ways you can test a geofence, by walking to the actual geofenced location, or testing it in the simulator. If you want to test it in the simulator, this video should give you everything you need.
- When you trigger the geofence, you should see the notification pop up on the screen
- Congrats — You did it!
- No go out and create some awesome location based experiences for your users
Let me know if this worked for you (it does for me!) and if you have any feedback.
Want to track enter and exit events from your geofences on Mixpanel? Check out how