【问题标题】:LocationManager crash when app wakes for update应用唤醒更新时 LocationManager 崩溃
【发布时间】:2016-06-25 16:11:46
【问题描述】:

虽然在应用程序处于活动状态时它可以正常工作,但在应用程序终止并唤醒以更新位置时它会崩溃

我处理应用程序的代码在didFinishLaunchingWithOptions 上为位置更新而唤醒

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()
    var glat : String = ""
    var glong : String = ""

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

         if launchOptions?[UIApplicationLaunchOptionsLocationKey] != nil {
  let locationManager = CLLocationManager() //or without this line, both crashes
                    locationManager.delegate = self
                    locationManager.desiredAccuracy = kCLLocationAccuracyBest
                    let status = CLLocationManager.authorizationStatus()
                    if (status == CLAuthorizationStatus.AuthorizedAlways) {
                        locationManager.startMonitoringSignificantLocationChanges()
                    }
                }
return true
    }

这是 AppDelegate 上的 locationmanager 委托

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

            if  let lat = manager.location?.coordinate.latitude,
                let long = manager.location?.coordinate.longitude {
                print(glat + " " + glong)

                glat = String(lat)
                glong = String(long)

                //Line 339
                updateloc(String(lat), long: String(long))
            }
    }

向服务器发送位置信息的功能

func updateloc(lat : String, long : String) {

        let session = NSURLSession.sharedSession()

        //Line 354
        let request = NSMutableURLRequest(URL: NSURL(string: "URLTO/updateloc.php")!)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = "POST"
        let data = "lat=\(lat)&long=\(long)"
        request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)

        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
            if let error = error {
                print(error)
            }
            if let response = response {

                let res = response as! NSHTTPURLResponse
                dispatch_async(dispatch_get_main_queue(), {
                    if (res.statusCode >= 200 && res.statusCode < 300)
                    {
                        do{
                            let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())

                            var success = 0


                            if let dictJSON = resultJSON as? [String:AnyObject] {
                                if let successInteger = dictJSON["success"] as? Int {
                                    success = successInteger

                                    if success == 1
                                    {
                                    print("ok")
                                    }


                                } else {
                                    print("no 'success' key in the dictionary, or 'success' was not compatible with Int")
                                }
                            } else {
                                print("unknown JSON problem")
                            }


                        } catch _{
                            print("Received not-well-formatted JSON")
                        }

                    }
                })
            }
        })
        task.resume()


    }

这是崩溃日志

Crashed: com.apple.main-thread
0                          0x10015d998 specialized AppDelegate.updateloc(String, long : String) -> () (AppDelegate.swift:354)
1                          0x10015ddf8 specialized AppDelegate.locationManager(CLLocationManager, didUpdateLocations : [CLLocation]) -> () (AppDelegate.swift:339)
2                          0x100159d0c @objc AppDelegate.locationManager(CLLocationManager, didUpdateLocations : [CLLocation]) -> () (AppDelegate.swift)
3  CoreLocation                   0x1893d08b8 (null) + 21836
4  CoreLocation                   0x1893ccaac (null) + 5952
5  CoreLocation                   0x1893c6e48 (null) + 880
6  CoreFoundation                 0x18262cf84 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 20
7  CoreFoundation                 0x18262c8bc __CFRunLoopDoBlocks + 308
8  CoreFoundation                 0x18262ad04 __CFRunLoopRun + 1960
9  CoreFoundation                 0x182554c50 CFRunLoopRunSpecific + 384
10 GraphicsServices               0x183e3c088 GSEventRunModal + 180
11 UIKit                          0x18783e088 UIApplicationMain + 204
12                         0x10015a324 main (AppDelegate.swift:20)

当应用在startMonitoringSignificantLocationChanges 模式下因位置更新而唤醒时应用崩溃

我真的看不出这里有什么错误。任何人都可以帮我解决它吗?

【问题讨论】:

  • 当您有字符串glatglong 时,为什么还要调用updateloc(String(lat), long: String(long))? String 构造函数是否有可能返回nil?你也知道崩溃发生在哪一行吗?
  • 但是当应用程序处于前台时,相同的功能可以正常工作吗?是的,我在代码中显示了这些行。
  • 我在崩溃日志中看到 CoreLocation 为 (null),这是什么意思?
  • 在文档中写道:当应用程序唤醒时,您有少量时间(取决于操作系统版本)来执行一些人员。位置上传是否需要操作系统提供的更多时间。出于这个原因,它正在扼杀你的应用程序。您可以尝试使用后台任务进行上传。
  • @Ramis 你能告诉我怎么做吗?

标签: ios swift crash cllocationmanager


【解决方案1】:

作为起点,我建议将您的位置管理器功能移到一个单独的类中,并让您的位置类订阅 UIApplicationDidFinishLaunchingNotification 通知来处理应用重新启动时发生的情况。

实现这一点的一种方法是让您的班级成为单身人士,并让它通过 NSNotificationCenter 中继位置更新。

startMonitoringSignificantLocationChanges 如果在应用程序被操作系统终止时启用,它将在后台唤醒您的应用程序。

根据您想要实现的目标,您可以订阅两个不同的事件并根据应用委托事件开始停止相关的位置服务。

作为一个广泛的(在黑暗中拍摄)示例:

class LocationCommander {

    let locationManager = CLLocationManager()
    let defaultCenter = NSNotificationCenter.defaultCenter()
    //- NSUserDefaults - LocationServicesControl_KEY to be set to TRUE when user has enabled location services.
    let UserDefaults = NSUserDefaults.standardUserDefaults()
    let LocationServicesControl_KEY = "LocationServices"

    init(){
        defaultCenter.addObserver(self, selector: #selector(self.appWillTerminate), name: UIApplicationWillTerminateNotification, object: nil)
        defaultCenter.addObserver(self, selector: #selector(self.appIsRelaunched), name: UIApplicationDidFinishLaunchingNotification, object: nil)
    }

    func appIsRelaunched (notification: NSNotification) {

        //- Stops Significant Location Changes services when app is relaunched
        self.locationManager.stopMonitoringSignificantLocationChanges()

        let ServicesEnabled = self.UserDefaults.boolForKey(self.LocationServicesControl_KEY)

        //- Re-Starts Standard Location Services if they have been enabled by the user
        if (ServicesEnabled) {
            self.updateLocation()
        }
    }

    func appWillTerminate (notification: NSNotification){

        let ServicesEnabled = self.UserDefaults.boolForKey(self.LocationServicesControl_KEY)

        //- Stops Standard Location Services if they have been enabled
        if ServicesEnabled {

            self.locationManager.stopUpdatingLocation()

            //- Start Significant Location Changes to restart the app
            self.locationManager.startMonitoringSignificantLocationChanges()
        }

        NSUserDefaults.standardUserDefaults().synchronize()
    }

    func updateLocation () {

        if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized){

            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            self.locationManager.distanceFilter = kCLDistanceFilterNone

            self.locationManager.startUpdatingLocation()

            //- Save Location Services ENABLED to NSUserDefaults
            self.UserDefaults.setBool(true, forKey: self.LocationServicesControl_KEY)
        } else {
            //- Unauthorized, requests permissions
        }
    }
}

请记住,此代码尚未经过测试,我提取了一个旧项目的片段,由于语言更新,这些片段可能会出现一些语法错误。

总的来说,我们正在这样做:

  • 订阅相关通知
  • 当应用程序即将终止时,检查我们是否正在获取位置更新,如果是,则停止标准服务并启动重大更改服务以在有新更新可用时唤醒应用程序。
  • 当应用唤醒时,它将通知类,该类将决定我们是否继续跟踪通知更新(基于 NSUserDefaults 中存储的值)。

您的应用可能会因为实例化一个新的位置管理器而崩溃,然后该管理器会尝试重新启动可能已经在运行的位置服务。

我希望这会有所帮助!

【讨论】:

  • 据我所知,当应用程序终止时,不需要启用后台位置更新以使重要位置更改工作?
  • 浏览文档似乎你是对的,但是文档提到“在唤醒时间,应用程序被置于后台并且你有一小段时间(大约 10 秒) 手动重新启动位置服务并处理位置数据” - 这可能需要启用后台位置更新以允许应用在后台重新启动位置服务。
【解决方案2】:

文档说

对于重新启动应用程序的服务,系统会将 UIApplicationLaunchOptionsLocationKey 键添加到在启动时传递给应用程序委托的选项字典中。当此密钥存在时,您应该立即重新启动应用的位置服务。选项字典不包含有关位置事件本身的信息。您必须配置一个新的位置管理器对象并再次委托和启动您的位置服务以接收任何未决事件。

它还说:

连续多次调用此方法 [表示startMonitoringSignificantLocationChanges] 不会自动生成新事件。但是,在这两者之间调用 stopMonitoringSignificantLocationChanges 确实会导致在您下次调用此方法时发送一个新的初始事件。

这意味着乍看之下可能很清楚。首先,位置更新触发了您的应用重新启动这一事实并不意味着您可以立即通过代理的locationManager:didUpdateLocations: 方法获得它。其次,如果您处于后台(因此没有重新启动,而是刚开始活跃!),又是不同的。事实上,我看到人们遇到的一个常见问题是他们不知道他们是在后台(非活动)还是终止/刚刚重新启动。您甚至无法轻松测试/看到这一点,因为按两次主页按钮时仍会显示被系统终止的应用程序。检查 XCode 的 Debug 菜单中 Attach to Process... 下显示的列表,以查看您的应用程序是否仍在运行(并且在后台)(顺便说一句,如果您想玩,通过 XCode 中的停止按钮终止应用程序会导致这种不一致您可以通过各种方式变得活跃或重新启动)。我之所以在这里提到这一点,是因为很多问题都在问“当我的应用再次激活时,X 怎么会发生?”并且回答的人假设的事情与提问者的意思不同。

无论如何,如果您的应用实际上已经重新启动,您的 locationManager 变量现在包含一个全新的实例,您应该在调用 startMonitoringSignificantLocationChanges 后立即获得更新。我将在下面解决您可能仍会遇到的问题。 如果您的应用程序刚刚再次激活,您应该再次调用stopMonitoringSignificantLocationChanges,然后再次调用startMonitoringSignificantLocationChanges 以立即获取更新(简而言之:始终停止然后开始正确重启,即使您尚未运行也不会受到伤害)。

现在我认为这个问题(部分)是由于 Apple 在位置更新后重新启动的方式造成的混乱。如果不使用您的代码,我不完全确定会发生什么,但我希望这会有所帮助: 在您的application:didFinishLaunchingWithOptions: 方法中,您使用let locationManager = CLLocationManager() 设置一个局部常量。 这个然后重新启动并触发位置更新。然而,它可能在委托的locationManager:didUpdateLocations: 方法被调用之前被释放,毕竟回调是异步发生的(application:didFinishLaunchingWithOptions: 可能在调用之前返回)。我不知道它是如何或为什么起作用的,并且正如你所说的那样,也许是运气,或者它与 CLLocationManager 内部的工作方式有关。无论如何,我认为然后发生的是,在locationManager:didUpdateLocations: 中,您不再获得有意义的位置数据,因为负责调用的CLLocationManager 实例不再有效。 latlong 为空甚至为零,并且您的请求的 URL(您没有显示)无效。

我建议先:

  1. 确保在application:didFinishLaunchingWithOptions: 中正确设置了类的常量locationManager(在您检查了UIApplicationLaunchOptionsLocationKey 标志的存在之后)。去掉同名的局部常量。
  2. 停止然后重新启动位置更新。这应该立即使用最新的位置数据(触发您的应用重新启动或再次激活的位置数据)调用您的代理的 locationManager:didUpdateLocations: 方法。
  3. 确保在locationManager:didUpdateLocations: 方法中获得有意义的数据。如果不是这种情况,请不要调用 updateloc(在将类的变量设置为新值之后,您可能还想将行 print(glat + " " + glong) 移动到,以便在控制台上查看您得到的内容是否有意义)。

有一件小事我无法告诉我:如果您的应用程序刚刚再次激活(而不是重新启动),我不确定是否设置了 UIApplicationLaunchOptionsLocationKey。你可能也想调查那个。如果从这个意义上说变得活跃不是“重新启动”,那么你的locationManager 无论如何应该仍然很高兴工作,至少这是我从文档中得到的(而且它一直是自从我自己尝试过一段时间以来)。如果您仍然遇到问题,请告诉我/我们,我很好奇结果如何。:)

【讨论】:

  • 有没有办法在不使用委托的情况下获取位置?我想我记得当应用程序唤醒时,位置属性也充满了位置信息?
  • 我从未使用过它,但是是的,文档声称您可以从locationManager.location 获得最新的,如果记忆正确的话。不过,您可能必须为此开始跟踪,我不确定也无法检查 atm。但是,请务必检查您传递给 updateloc 方法的内容。 :)
【解决方案3】:

试试这个

dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_DEFAULT.rawValue), 0)) {
          updateloc(String(lat), long: String(long))   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多