iOS调试位置监控当应用程序从模拟器中关闭时

3
似乎我的应用在终止状态下没有启动并调用位置更新。由于在办公室内来回移动以触发重要的位置更改不是一件容易的事情,所以很难测试不起作用的内容。是否有一种方法可以在模拟器中模拟位置更改,同时关闭应用程序?我已经尝试使用“模拟器>调试>位置>[城市自行车骑行,... ]”,但似乎仅在应用程序运行时才有效。我甚至尝试创建一个方案,在编译后不会自动启动应用程序。您有任何建议如何调试此类问题吗?(到目前为止,我只是在每次应用程序启动时记录在单独的文件中,即使不幸的是,当应用程序处于关闭状态时,应用程序也不会在后台启动)这是我的应用程序委托中的代码:
    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])不会被调用:

enter image description here

1个回答

0
你尝试过使用自定义位置而不是城市自行车骑行吗?我的一个应用程序使用区域监控,如果我手动提供位置,则即使锁定模拟器,它也可以工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接