如何在用户进入CLLocation时通知用户?
情况:
我按照以下教程:
https://www.raywenderlich.com/95014/geofencing-ios-swift
问题:
永远不会触发以下function:
AppDelegate.swift
func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) { if region is CLCircularRegion { handleRegionEvent(region) } } func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) { if region is CLCircularRegion { handleRegionEvent(region) } } func handleRegionEvent(region: CLRegion!) { print("Geofence triggered!") // Show an alert if application is active if UIApplication.sharedApplication().applicationState == .Active { if let message = notefromRegionIdentifier(region.identifier) { if let viewController = window?.rootViewController { showSimpleAlertWithTitle("Congratulations", message: "You just found: " + message , viewController: viewController) } } } else { // Otherwise present a local notification let notification = UILocalNotification() notification.alertBody = "You just found: " + notefromRegionIdentifier(region.identifier)! notification.soundName = "Default"; UIApplication.sharedApplication().presentLocalNotificationNow(notification) } }
题:
本教程是为iOS 8编写的。我目前在iOS 9.3上。 在您看来是什么导致了这个问题,我该如何解决?
确保两件事: –
1.)您已将这些添加到viewDidLoad()
: –
locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = kCLDistanceFilterNone locationManager.requestWhenInUseAuthorization() locationManager.startMonitoringSignificantLocationChanges() locationManager.startUpdatingLocation()
requestWhenInUseAuthorization()
和startUpdatingLocation()
初始化的另一种替代方法,特别是Swift 2.2,因为在Swift 2.2中,不推荐使用选择器的字符串文字,而是需要使用这个新的运算符#selector。 : –
你也可以使用: –
locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = kCLDistanceFilterNone locationManager.startMonitoringSignificantLocationChanges() if locationManager.respondsToSelector(#selector(locationManager.requestWhenInUseAuthorization)) { locationManager.requestWhenInUseAuthorization() } else { locationManager.startUpdatingLocation() } //Prefer the FIRST ONE.
2.)您已将info.plist更新为: –
NSLocationAlwaysUsageDescription : String :-> I need location.
NSLocationWhenInUseUsageDescription: String :-> I need location.
privacy - location usage description: String :-> I need location.
根据应用的需要编辑I need location
PS: – 如果它仍然没有调用你的locationManager
函数
模拟器: – 在模拟器设置中查找应用程序的location
设置。
设备: – 进入settings > Privacy > Location services > Your app > Always.
您也可能会发现此解释很有用: – https://stackoverflow.com/a/26090094/6297658
您没有显示用于设置CL的代码 – 这可能是您的问题所在。
你编辑info.plist了吗?
你要求许可吗?
您是否在CL管理器上调用了其中一个启动function?
在应用程序委托中初始化您的位置管理器已完成启动