【问题标题】:iOS debug location monitoring when app is closed from simulator从模拟器关闭应用程序时的iOS调试位置监控
【发布时间】:2016-07-12 06:30:17
【问题描述】:

当我的应用程序处于终止状态时,它似乎没有启动并调用位置更新。

由于我很难测试什么不起作用(当您必须在办公室内来回移动以尝试触发重大位置更改时,使用真实设备并不容易),是否存在关闭应用时如何在模拟器中模拟位置变化?

我已经尝试过使用 Simulator > Debug > Location > [City Bicyce Ride, ...] 但它似乎只在应用程序运行时才有效。我什至尝试创建一个应用程序在编译后不会自动启动的方案。

您对如何调试此类问题有任何建议吗? (到目前为止,我只是在每次应用程序启动时登录单独的文件,即使不幸的是,当处于关闭状态时应用程序没有在后台启动)

这是我的应用委托中的代码:

    lazy var locationManagerFitness: CLLocationManager! = {
        let manager = CLLocationManager()
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.distanceFilter = 1.0
        manager.activityType = CLActivityType.Fitness
        manager.delegate = self
        manager.requestAlwaysAuthorization()
        return manager
    }()

    func startLocationMonitoring()
    {
        locationManagerFitness.stopMonitoringSignificantLocationChanges()
        locationManagerFitness.startUpdatingLocation()
    }

    func startLocationMonitoringSignificantChanges()
    {
        locationManagerFitness.stopUpdatingLocation()
        locationManagerFitness.startMonitoringSignificantLocationChanges()
    }

    // MARK: - CLLocationManagerDelegate

   func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {

        if manager == locationManagerFitness
        {
            log.debug("locationManagerFitness:")
        }

        for newLocation in locations
        {
            saveLocation(newLocation)

            if UIApplication.sharedApplication().applicationState == .Active {
                log.debug("App is active. New location is \( newLocation )")
            } else {
                log.debug("App is in background. New location is \( newLocation )")
            }
        }

    }

    func saveLocation(location: CLLocation) -> Location {

        let entity =  NSEntityDescription.entityForName("Location",
                                                        inManagedObjectContext:managedObjectContext)
        let locationCD = NSManagedObject(entity: entity!,
                                         insertIntoManagedObjectContext: managedObjectContext) as! Location

        locationCD.setValue(location.coordinate.latitude, forKey: "latitude")
        locationCD.setValue(location.coordinate.longitude, forKey: "longitude")
        locationCD.setValue(NSDate(), forKey: "creationDate")

        do {
            try managedObjectContext.save()
        } catch let error as NSError  {
            print("Could not save \(error), \(error.userInfo)")
        }

        return locationCD
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
-> Bool {


        //Logs
        let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

        let dayTimePeriodFormatter = NSDateFormatter()
        dayTimePeriodFormatter.dateFormat = "hh:mm_dd-MM-yyyy"
        let dateString = dayTimePeriodFormatter.stringFromDate(NSDate())
        let logURL = documentDirectoryURL.URLByAppendingPathComponent("log_\( dateString ).txt")
        log.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logURL, fileLogLevel: .Debug)

        log.debug("Starting app...")

        // StatusBar
        UIApplication.sharedApplication().statusBarStyle = .LightContent

        switch CLLocationManager.authorizationStatus()
        {
        case .AuthorizedAlways:
            if let _ = launchOptions?[UIApplicationLaunchOptionsLocationKey]
            {
                startLocationMonitoringSignificantChanges()
            }
        default:
            break;
        }

        log.debug("App started!")

        return true
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        log.debug("startLocationMonitoringSignificantChanges")
        startLocationMonitoringSignificantChanges()
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        log.debug("startLocationMonitoring")
        startLocationMonitoring()
    }

上述代码的行为是应用程序仅在其处于活动状态时才监控用户位置变化。 看下图很明显,模拟器似乎继​​续移动自行车骑行的位置,但是 AppDelegate CLLocationManagerDelegate 的 locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 在应用程序终止或在后台时不会被调用:

【问题讨论】:

    标签: ios xcode swift ios-simulator cllocationmanager


    【解决方案1】:

    您是否尝试过自定义位置而不是 City Bycle Ride?我的一个应用程序使用了区域监控,如果我手动提供位置,那么即使我锁定了模拟器,它也可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-02
      • 2013-07-13
      • 2015-03-17
      • 2012-06-23
      • 2013-08-26
      • 2023-03-12
      • 2012-04-24
      • 2014-02-18
      相关资源
      最近更新 更多