收到背景位置时应用程序崩溃

Utk*_*maz 7 crash cllocationmanager ios swift

我正在尝试在后台将位置更新发送到服务器

应用程序有时会在后台崩溃

这是我的 locationmanager delegate

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

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

                if UIApplication.shared.applicationState == .background {
                self.updatebackloc(lat, long: long)
                }

                if UIApplication.shared.applicationState == .active {
                self.updateloc(lat, long: long)
                    locationManager.stopUpdatingLocation()
                    let status = CLLocationManager.authorizationStatus()
                    if (status == CLAuthorizationStatus.authorizedAlways) {
                    locationManager.startMonitoringSignificantLocationChanges()
                    }
                }
            }
            }
Run Code Online (Sandbox Code Playgroud)

这是updatebacklog函数

func updatebackloc(_ lat: CLLocationDegrees, long: CLLocationDegrees) {
        let userID = TegKeychain.get("userID")!
        let parameters: Parameters = ["userID": userID, "lat": lat, "long":long]
        Alamofire.request("https://xxxxx.com/ios/updatebackloc.php", method: .post, parameters: parameters).validate().responseJSON { response in
            switch response.result {
            case .success:
                if let json = response.result.value {
                    var success = 0
                    if let dictJSON = json as? [String: AnyObject] {
                        if let successInteger = dictJSON["success"] as? Int {
                            success = successInteger
                            if success == 1
                            {

                            }
                        }
                    }
                }
            case .failure(_):
                return
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

didFinishLaunchingWithOptions 部分

if let _ = launchOptions?[UIApplicationLaunchOptionsKey.location] {
                    startSignificationLocation()
                }
Run Code Online (Sandbox Code Playgroud)

startSignificationLocation 触发功能 didFinishLaunchingWithOptions

func startSignificationLocation() {
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.startMonitoringSignificantLocationChanges()
    }
Run Code Online (Sandbox Code Playgroud)

这是崩溃日志

Crashed: com.apple.main-thread
0                          0x10285b798 specialized AppDelegate.updatebackloc(Double, long : Double) -> () + 4339644312
1                          0x10285b8e4 specialized AppDelegate.locationManager(CLLocationManager, didUpdateLocations : [CLLocation]) -> () (AppDelegate.swift:396)
2                          0x1028540c0 @objc AppDelegate.locationManager(CLLocationManager, didUpdateLocations : [CLLocation]) -> () (AppDelegate.swift)
3  CoreLocation                   0x1874f97bc (null) + 77412
4  CoreLocation                   0x1874f901c (null) + 75460
5  CoreLocation                   0x1874e16b4 (null) + 1004
6  CoreFoundation                 0x180ea3590 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 20
7  CoreFoundation                 0x180ea2e60 __CFRunLoopDoBlocks + 288
8  CoreFoundation                 0x180ea10c8 __CFRunLoopRun + 2436
9  CoreFoundation                 0x180dc0c58 CFRunLoopRunSpecific + 436
10 GraphicsServices               0x182c6cf84 GSEventRunModal + 100
11 UIKit                          0x18a5195c4 UIApplicationMain + 236
12                         0x1027fe524 main (InboxInterests.swift:30)
13 libdyld.dylib                  0x1808e056c start + 4
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这是代码

在此输入图像描述

代码为文本

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

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

            if UIApplication.shared.applicationState == .background {
            self.updatebackloc(lat, long: long)
            }

            if UIApplication.shared.applicationState == .active {
            self.updateloc(lat, long: long)
                locationManager.stopUpdatingLocation()
                let status = CLLocationManager.authorizationStatus()
                if (status == CLAuthorizationStatus.authorizedAlways) {
                locationManager.startMonitoringSignificantLocationChanges()
                }
            }
        }
        }

        func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
            print(error)
        }


        func updateloc(_ lat: CLLocationDegrees, long: CLLocationDegrees) {
            let userID = TegKeychain.get("userID")!
            let parameters: Parameters = ["userID": userID, "lat": lat, "long":long]
            Alamofire.request("https://xxxxx.com/ios/updateloc.php", method: .post, parameters: parameters).validate().responseJSON { response in
                switch response.result {
                case .success:
                    if let json = response.result.value {
                        var success = 0
                        if let dictJSON = json as? [String: AnyObject] {
                            if let successInteger = dictJSON["success"] as? Int {
                                success = successInteger
                                if success == 1
                                {

                                }
                            }
                        }
                    }
                case .failure(_):
                    return
                }
            }
        }
    func updatebackloc(_ lat: CLLocationDegrees, long: CLLocationDegrees) {
        guard let userID = TegKeychain.get("userID") else {
            return
        }
        let parameters: Parameters = ["userID": userID, "lat": lat, "long":long]
        Alamofire.request("https://xxxxx.com/ios/updatebackloc.php", method: .post, parameters: parameters).validate().responseJSON { response in
            switch response.result {
            case .success:
                if let json = response.result.value {
                    var success = 0
                    if let dictJSON = json as? [String: AnyObject] {
                        if let successInteger = dictJSON["success"] as? Int {
                            success = successInteger
                            if success == 1
                            {

                            }
                        }
                    }
                }
            case .failure(_):
                return
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

sha*_*ght 10

我非常怀疑你是在试图强行解开nil这一行中的一个值:

let userID = TegKeychain.get("userID")!
Run Code Online (Sandbox Code Playgroud)

要弄清楚我是否正确,请尝试修复崩溃(但仍然没有做你想要的事情):

guard let userID = TegKeychain.get("userID") else {
    return
}
Run Code Online (Sandbox Code Playgroud)

假设TegKeychain.get("userID")正在尝试从系统KeyChain获取密钥的值,则该值很可能已被写入具有不适合的可访问性的KeyChain.因此,您不能在后台访问它并nil返回.

要解决此问题,请kSecAttrAccessible在将凭证保存到KeyChain时设置一个符合键需求的值.

Apple推荐使用kSecAttrAccessibleAfterFirstUnlock,可能符合您的需求.

在代码中:

let userIdToSave = "secretString"
guard let secretAsData = userIdToSave.data(using: String.Encoding.utf8) else {
    return
}
let keyChainKey = "userID"
let query = [
    kSecClass as String: kSecClassGenericPassword as String,
    kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock as String,
    kSecAttrService as String: yourService,
    kSecAttrAccount as String: keyChainKey,
    kSecValueData as String: secretAsData] as [String : Any]

SecItemDelete(query as CFDictionary)

let status = SecItemAdd(query as CFDictionary, nil)
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看Apple文档.


编辑:

根据您在评论中的陈述,我的猜测是错误的.

我的下一个猜测是,操作系统正在网络进程中杀死你.您可以通过向操作系统询问更多时间来避免这种情况.

为此,请启动backgroundTask.

代码看起来像这样:

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    var bgTask = UIBackgroundTaskInvalid

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        if let _ = launchOptions?[UIApplicationLaunchOptionsKey.location] {
            // app is launched in backgrond due to location change
            bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: { // Start background task
                UIApplication.shared.endBackgroundTask(bgTask)
                bgTask = UIBackgroundTaskInvalid
            })
            startSignificationLocation()
        }
        return true
    }

    // ... your other methods

    func updatebackloc(_ lat: CLLocationDegrees, long: CLLocationDegrees) {
        guard let userID = TegKeychain.get("userID") else {
            return
        }
        let parameters: Parameters = ["userID": userID, "lat": lat, "long":long]
        Alamofire.request("https://xxxxx.com/ios/updatebackloc.php", method: .post, parameters: parameters).validate().responseJSON { response in
            defer {
                // Tell the OS that you are done
                UIApplication.shared.endBackgroundTask(bgTask)
                bgTask = UIBackgroundTaskInvalid
            }
            switch response.result {
            case .success:
                if let json = response.result.value {
                    var success = 0
                    if let dictJSON = json as? [String: AnyObject] {
                        if let successInteger = dictJSON["success"] as? Int {
                            success = successInteger
                            if success == 1
                            {

                            }
                        }
                    }
                }
            case .failure(_):
                return
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,请不要忘记在其他答案中提及所需的Capatibilities:

在此输入图像描述

你还应该做更多的调试.阅读本文,了解如何在Xcode中模拟运动.


ahb*_*bou 1

您需要将后台位置调用包装在 UIBackgroundTask 内。

var bgTask: UIBackgroundTaskIdentifier?
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.

    bgTask = application.beginBackgroundTask(withName: "bgLocation", expirationHandler: {
        if let task = self.bgTask {
            application.endBackgroundTask(task)
            self.bgTask = UIBackgroundTaskInvalid
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

然后,在调用 updatebackloc 函数时,使用正确的后台队列并结束后台任务。

就像是:

func updatebackloc(_ lat: CLLocationDegrees, long: CLLocationDegrees) {
    let userID = TegKeychain.get("userID")!
    let parameters: Parameters = ["userID": userID, "lat": lat, "long":long]
    DispatchQueue.global().async {
        Alamofire.request("https://xxxxx.com/ios/updatebackloc.php", method: .post, parameters: parameters).validate().responseJSON { response in

            //response handling here...
            //....
            if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
                if let task = appDelegate.bgTask {
                    UIApplication.shared.endBackgroundTask(task)
                    appDelegate.bgTask = UIBackgroundTaskInvalid
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)