最近开发遇到了APP莫名的闪退的问题,后来查阅stackview文献得出结论是系统线程导致的在此记录一下
事件经过
在日历中添加事件的回调中更新UI事件,未声明在主线程操作,导致莫名闪退
解决方案
使用DispatchQueue.main.async {}更新UI
结果
不再闪退
源码
let eventStore = EKEventStore.init()
eventStore.requestAccess(to: .event) { (granted, error) in
if error != nil {
DispatchQueue.main.async {
ToastView.show(withTitle: "保存日历出错了")
self.noticeBtn.isSelected = false
}
} else {
if granted == false {
DispatchQueue.main.async {
ToastView.show(withTitle: "请开启日历权限")
self.noticeBtn.isSelected = false
}
} else {
DispatchQueue.main.async {
// 创建日程
let event = EKEvent.init(eventStore: eventStore)
event.title = "日历内容"
event.notes = "日历内容"
event.startDate = Date(timeIntervalSince1970: TimeInterval(_startTime))
event.endDate = Date(timeIntervalSince1970: TimeInterval(_startTime + 3600))
event.isAllDay = false
//日程提醒
let alarm = EKAlarm.init(relativeOffset: -60.0)
event.addAlarm(alarm)
event.calendar = eventStore.defaultCalendarForNewEvents
// 保存到系统
var result: ()?
do {
result = try eventStore.save(event, span: .thisEvent)
} catch {}
if result != nil {
self.noticeBtn.setImage(UIImage(named: ""), for: .selected)
ToastView.show(withTitle: "日历提醒已开启")
}
}
}
}
}