我有一个在启动时崩溃的应用程序。我已经确定了问题的根源,但似乎无法弄清楚该如何解决。首先让我解释一下我的工作:
我有一个LocationManager,用于检查用户是否输入了某个区域(使用startRegionMonitoring)。如果是这样,则计划在5分钟内触发本地通知。但是,如果此人在这5分钟内再次离开,则取消本地通知。我这样做是因为用户可以直接经过建筑物而无需实际进入建筑物。当用户自己打开应用程序时,它还会取消所有待处理的通知(在这5分钟之内)。
发生这种情况时,应用程序在启动时崩溃。崩溃报告指出了这一点:
Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x000000010098b38c
Triggered by Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 GetReminded 0x000000010098b38c closure #1 in closure #1 in AppDelegate.applicationWillEnterForeground(_:) + 3388300 (AppDelegate.swift:1300)
1 GetReminded 0x00000001006be738 thunk for @escaping @callee_guaranteed () -> () + 452408 (<compiler-generated>:0)
2 libdispatch.dylib 0x00000001b6448a38 0x1b63e9000 + 391736
3 libdispatch.dylib 0x00000001b64497d4 0x1b63e9000 + 395220
4 libdispatch.dylib 0x00000001b63f7004 0x1b63e9000 + 57348
5 CoreFoundation 0x00000001b699ac1c 0x1b68f1000 + 695324
6 CoreFoundation 0x00000001b6995b54 0x1b68f1000 + 674644
7 CoreFoundation 0x00000001b69950b0 0x1b68f1000 + 671920
8 GraphicsServices 0x00000001b8b9579c 0x1b8b8b000 + 42908
9 UIKitCore 0x00000001e31c4978 0x1e2908000 + 9161080
10 GetReminded 0x0000000100681f4c main + 204620 (ExerciseStatistics.swift:219)
11 libdyld.dylib 0x00000001b645a8e0 0x1b6459000 + 6368
起初,我没有对主线程执行取消操作-这是我认为导致崩溃的原因。因此,我使用了Dispatch Queue,并认为该问题将得到解决,但是仍然存在。我的willEnterForeground
代码:
UNUserNotificationCenter.current().getDeliveredNotifications { (notifications: [UNNotification]) in
DispatchQueue.main.async {
for notification in notifications {
if(notification.request.content.userInfo["notificationType"] as! String == "exitReminder" || notification.request.content.userInfo["notificationType"] as! String == "enterReminder") {
let notificationID = notification.request.identifier
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [notificationID])
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notificationID])
}
}
}
}
我不太确定如何解决此问题。重要的是要知道此提醒是从后台发送的,所以当应用不在前台时。我在后台启用了定位服务,当我停留在该位置时一切正常,但是当我在5分钟内再次退出时会出错,因此需要取消通知。
有什么想法吗?
答案 0 :(得分:0)
notification.request.content.userInfo["notificationType"] as! String
(或字符串以外的内容), nil
将崩溃。如果没有充分的理由,您不应该使用强制降落。
使用防御性编码:
for notification in notifications {
if let notificationType = notification.request.content.userInfo["notificationType"] as? String {
if notificationType == "exitReminder" || notificationType == "enterReminder" {
let notificationID = notification.request.identifier
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [notificationID])
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notificationID])
}
}
}