Detecting application crash in XCode/swift -
for os x app persistent state, there anyway programatically detect whether last time application open, crashed, or closed unexpectedly? (so can perform actions ensure application in consistent state)
you can use nssetuncaughtexceptionhandler
described here.
nssetuncaughtexceptionhandler { exception in print("exception: \(exception.name) \(exception.reason!) \(exception.description)") print(exception.callstacksymbols) }
the code using is...
nssetuncaughtexceptionhandler { exception in exceptionmanager.handle(exception) }
and exceptionmanager class includes...
class exceptionmanager { class func handle(exception: nsexception) { var exceptions = [exceptionitem]() if let items = nsuserdefaults.standarduserdefaults().arrayforkey("uncaughtexceptions") as? [nsdata] { item in items { if let exception = nskeyedunarchiver.unarchiveobjectwithdata(item) as? exceptionitem { exceptions.append(exception) } } } let newitem = exceptionitem(nsdate(), exception) exceptions.insert(newitem, atindex: 0) if exceptions.count > 5 { // keep last 5 exceptions exceptions = array(exceptions[0..<5]) } var items = [nsdata]() e in exceptions { let item = nskeyedarchiver.archiveddatawithrootobject(e) nsdata items.append(item) } nsuserdefaults.standarduserdefaults().setobject(items, forkey: "uncaughtexceptions") }
Comments
Post a Comment