iPhone(Swift)でGeofencing!
通常SwiftでGeofencingをやろうとするとUILocalNotificationのscheduleLocalNotificationを活用した例が出てきます。
しかしこの状態だと出入りした時2つのイベントを拾ってしまいます。
場合によっては、入った時もしくは出た時のイベントのみ欲しいと時もあると思います。
AppDelegate.swift
//指定したフェンスに出入りした時に通知を出す
func notifications() {
let coordinate = CLLocationCoordinate2DMake(character.latitude,character.longitude)
let radius = 3000.0
let identifier = character.id
let notification = UILocalNotification()
notification.regionTriggersOnce = false
notification.alertBody = "指定したフェンスを出入りしたよ!"
notification.regionTriggersOnce = true
notification.region = CLCircularRegion(center: coordinate, radius: radius, identifier: identifier)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
解決方法
CLRegionのコードを読んだら定義を発見しました。
CLRegion.m
/*
* notifyOnEntry
*
* Discussion:
* App will be launched and the delegate will be notified via locationManager:didEnterRegion:
* when the user enters the region. By default, this is YES.
*/
@available(iOS 7.0, *)
public var notifyOnEntry: Bool
/*
* notifyOnExit
*
* Discussion:
* App will be launched and the delegate will be notified via locationManager:didExitRegion:
* when the user exits the region. By default, this is YES.
*/
@available(iOS 7.0, *)
public var notifyOnExit: Bool
CLCircularRegionの(notifyOnExit)もしくは(notifyOnEntry)をそれぞれ設定するだけ
.swift
let region = CLCircularRegion(center: coordinate, radius: radius, identifier: identifier)
region.notifyOnExit = false
region.notifyOnEntry = true
notifyOnExitとnotifyOnEntryを実装したコード
AppDelegate.swift
//指定したフェンスに入った時のみ通知をだす
func notifications() {
let coordinate = CLLocationCoordinate2DMake(character.latitude,character.longitude)
let radius = 3000.0
let identifier = character.id
let region = CLCircularRegion(center: coordinate, radius: radius, identifier: identifier)
region.notifyOnExit = false
region.notifyOnEntry = true
let notification = UILocalNotification()
notification.regionTriggersOnce = false
notification.alertBody = "指定したフェンスに入ったよ!"
notification.regionTriggersOnce = true
notification.region = region
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
参考資料
[Remove fired Location-Based notification when user exits region](https://firebase.google.com/docs/crash/ "Firebase Crash Reporting")