iBeacon Tutorial with iOS and Swift
Learn how you can find an iBeacon around you, determine its proximity, and send notifications when it moves away from you. By Owen L Brown.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
iBeacon Tutorial with iOS and Swift
30 mins
Notifications
Things feel pretty complete at this point; you have your list of iBeacons and can monitor their proximity in real time. But that isn't the end goal of your app. You still need to notify the user when the app is not running in case they forgot their laptop bag or their cat ran away — or worse, if their cat ran away with the laptop bag! :]
They look so innocent, don't they?
At this point, you've probably noticed it doesn't take much code to add iBeacon functionality to your app. Adding a notification when a cat runs away with your laptop bag is no different!
Open AppDelegate.swift and add the following import:
import CoreLocation
Next, make the AppDelegate
class conform to the CLLocationManagerDelegate
protocol by adding the following to the very bottom of AppDelegate.swift (below the closing brace):
// MARK: - CLLocationManagerDelegate
extension AppDelegate: CLLocationManagerDelegate {
}
Just as before, you need to initialize the location manager and set the delegate accordingly.
Add a new locationManager
property to the AppDelegate
class, initialized with an instance of CLLocationManager
:
let locationManager = CLLocationManager()
Then add the following statement to the very top of application(_:didFinishLaunchingWithOptions:)
:
locationManager.delegate = self
Recall that any regions you add for monitoring using startMonitoringForRegion(_:)
are shared by all location managers in your application. So the final step here is simply to react when Core Location wakes up your app when a region is encountered.
Add the following method to the class extension you added at the bottom of AppDelegate.swift, like so:
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
guard region is CLBeaconRegion else { return }
let content = UNMutableNotificationContent()
content.title = "Forget Me Not"
content.body = "Are you forgetting something?"
content.sound = .default()
let request = UNNotificationRequest(identifier: "ForgetMeNot", content: content, trigger: nil)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
Your location manager calls the above method when you exit a region, which is the event of interest for this app. You don't need to be notified if you move closer to your laptop bag — only if you move too far away from it.
Here you check the region to see if it's a CLBeaconRegion
, since it's possible it could be a CLCircularRegion
if you're also performing geolocation region monitoring. Then you post a local notification with the generic message "Are you forgetting something?".
In iOS 8 and later, apps that use either local or remote notifications must register the types of notifications they intend to deliver. The system then gives the user the ability to limit the types of notifications your app displays. The system does not badge icons, display alert messages, or play alert sounds if any of these notification types are not enabled for your app, even if they are specified in the notification payload.
Add the following to the top of of application(_:didFinishLaunchingWithOptions:)
:
// Request permission to send notifications
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.alert, .sound]) { (granted, error) in }
This simply says that the app wishes to display an alert and play a sound when it receives a notification.
Build and run your app; make sure that your app can see one of your registered iBeacons and put the app into the background by pressing the Home button — which is a real-world scenario given that you want the app to notify you whilst you're pre-occupied with something else — perhaps another Ray Wenderlich tutorial app? :]. Now move away from the iBeacon and once you're far enough away you'll see the notification pop up:
Where to Go From Here?
Didn't tie an iBeacon to your source code? You can download the final project here, with everything you've done in this tutorial.
You now have a very useful app for monitoring those things that you find tricky to keep track of. With a bit of imagination and coding prowess you could add a lot of really useful features to this app:
- Notify the user which item has moved out of range.
- Repeat the notification to make sure the user sees it.
- Alert the user when iBeacon is back in range.
This iBeacons tutorial merely scratches the surface of what's possible with iBeacons.
iBeacons aren't just limited to custom apps; you can use them with Passbook passes as well. If you ran a movie theater, for example; you could offer movie tickets as Passbook passes. When patrons walked up to the ticket taker with an iBeacon nearby, their app would present the ticket on their iPhone automatically!
If you have any questions or comments on this tutorial, or if you have any novel ideas for the use of iBeacons, feel free to join the discussion below!