这是我尝试使用CLLocationManager进行信标区域监视的简短版本。
我需要通知多个(少于20个)区域的进入/退出事件。
即使在后台,我也会得到一致的位置输入事件。在客户端视图中或背景中,我不会在前景中获取退出事件。
有一次,我成功地在后台获得了退出事件,但是我没有得到可变数量的信标区域去听。
该代码中是否存在任何总体约定/逻辑缺陷?

//------------------
/* Client View Controller - Main Profile View */
class ClientVC: UIViewController, ClientVC_Preferences_Protocol, OpenPreferencesProtocol, ClientVCProtocol {

	/* Reference to AppDelegate file where location manager resides */
	let appDelegate = UIApplication.shared.delegate as! AppDelegate
	override func viewDidLoad(){

		// .. Obtain some beacon info - not shown

		for beacon in beacons {
	        /* Create a region for each beacon and start monitoring */
	        var region = CLBeaconRegion(proximityUUID: UUID(uuidString:beacon.UUID)!, identifier: beacon.Identifier)
	        region.notifyEntryStateOnDisplay = true
	        region.notifyOnExit = true
	        region.notifyOnEntry = true
	        self.appDelegate.locationManager.startMonitoring(for: region)
	    }
	}

	/* Protocol function to alert client when exit event occured */
	func alertClient(businessName:String) {

        let notification = UILocalNotification()
        notification.alertBody = "Did you leave " + businessName + "?"
        UIApplication.shared.presentLocalNotificationNow(notification)

        let alertController = UIAlertController(title: businessName, message: "Did you leave?", preferredStyle: .alert)

        let okAction = UIAlertAction(title: "Yes, I Left!", style: UIAlertActionStyle.default) {
            UIAlertAction in
        	// .. Do some firebase work - not shown
        }

        let cancelAction = UIAlertAction(title: "No, I'm Here!", style: UIAlertActionStyle.cancel) {
            UIAlertAction in
            // .. Do some firebase work - not shown
        }

        alertController.addAction(okAction)
        alertController.addAction(cancelAction)

        self.present(alertController, animated:true, completion:nil)
    }
}

//------------------
/* AppDelegate */

/* Protocol connected to Client View Controller */
protocol ClientVCProtocol{
    func alertClient(businessName:String) /* Displays alert to client when exiting the region */
    func reloadTableView() /* Refreshes table view */
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

	/* Delegate for ClientVC Protocol - used to call methods */
	var ClientVCDelegate:ClientVCProtocol?

	/* Instantiate location manager */
	var locationManager = CLLocationManager()

	/* Triggered by entering a region */
	func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
        print("Enter event " + region.identifier)
        // .. Do some firebase work - not shown
	}

	/* Triggered by exiting a region */
	func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {

		/* Break set on this line to ensure whether or not this function is called */
		print("Exit Attempt")

		/* Gets business name associated with region and calls protocol function to ClientVC */
		if let beaconRegion = region as? CLBeaconRegion {
            self.getBusinessName(region: region){
                (result: String) in
                print("Exit event " + region.identifier)
                self.ClientVCDelegate?.alertClient(businessName:result)
            }
        }
	}

	/* Runs when application finishes launching - configures location manager */
	func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.fbRef = Database.database().reference()
        UIApplication.shared.registerUserNotificationSettings(
            UIUserNotificationSettings(types: .alert, categories: nil))

        /* Not sure how relevent all of these calls are */
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 2000
        if #available(iOS 9.0, *) {
            locationManager.allowsBackgroundLocationUpdates = true
        }
        locationManager.startMonitoringSignificantLocationChanges()
        locationManager.pausesLocationUpdatesAutomatically = true
        locationManager.requestAlwaysAuthorization()

        return true
    }
}

最佳答案

一个问题是,您只设置了在ViewController中监视的区域,如果您希望背景条目/退出事件着火,则应该在AppDelegate中这样做。
了解CoreLocation会跟踪您正在监视的区域,并在区域状态更改时自动将应用程序启动到后台但是,如果您在AppDelegate的CLLocationManager方法中设置didFinishLaunching、regions和设置delegate,它将只触发回调。

10-07 19:22
查看更多