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

标签 ios xcode swift ios-simulator cllocationmanager

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

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

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

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

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

    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()
    }

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

enter image description here

最佳答案

您是否尝试过自定义位置而不是城市骑自行车?我的一个应用程序使用了 Region Monitoring,如果我手动提供位置,那么即使我锁定了模拟器它也能正常工作。

关于从模拟器关闭应用程序时的 iOS 调试位置监控,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36204041/

相关文章:

ios - 命令行构建一个没有开发团队的 iOS 示例项目

ios - 如何使用 IB_DESIGNABLE 在 Storyboard中可视化可重用的 xib?

ios - 如何使 scrollView 像 Apple AppStore "Featured Page"一样?

ios - 从外部项目目录读取 plist 文件

ios - Docker设置-无法运行世界

ios - 状态栏颜色与 Pixate

ios - 无法将 NSString 从一个 VC 传递到下一个 VC

ios - 如何安装 CocoaPods?

ios - 更改 UICollectionView 中特定单元格的图像

ios - 交互转场+结束动画怎么做?