My Application is working fine if I open from home screen but when I open it from TestFlight application open button it crashes by giving the error that i obtained from Crashlytics.
#0. Crashed: com.apple.main-thread
0 ABC 0x4f1778 specialized AppDelegate.handleRemoteNotificationFromKilledState([NSObject : AnyObject]) -> () (AppDelegate.swift:183)
1 Abc 0x10f3b8 specialised static _VariantDictionaryStorage.maybeGetFromCocoaStorage(_CocoaDictionaryStorage, forKey : A) -> B? (ViewController.swift)
2 ABC 0x4f212c specialized AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [NSObject : AnyObject]?) -> Bool (AppDelegate.swift)
3 abc 0x4ed0dc #objc AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [NSObject : AnyObject]?) -> Bool (AppDelegate.swift)
4 UIKit 0x24f82a6f -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 394
5 UIKit 0x251ac287 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3086
6 UIKit 0x251b0241 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1588
7 UIKit 0x251c4811 __84-[UIApplication _handleApplicationActivationWithScene:transitionContext:completion:]_block_invoke3286 + 36
8 UIKit 0x251ad767 -[UIApplication workspaceDidEndTransaction:] + 134
9 FrontBoardServices 0x21ffbbf7 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 18
10 FrontBoardServices 0x21ffbaa7 -[FBSSerialQueue _performNext] + 226
11 FrontBoardServices 0x21ffbda5 -[FBSSerialQueue _performNextFromRunLoopSource] + 44
12 CoreFoundation 0x208ef9e7 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 14
13 CoreFoundation 0x208ef5d7 __CFRunLoopDoSources0 + 454
14 CoreFoundation 0x208ed93f __CFRunLoopRun + 806
15 CoreFoundation 0x2083c1c9 CFRunLoopRunSpecific + 516
16 CoreFoundation 0x2083bfbd CFRunLoopRunInMode + 108
17 UIKit 0x24f7bf37 -[UIApplication _run] + 526
18 UIKit 0x24f76435 UIApplicationMain + 144
19 abc 0x4ef4ec main (AppDelegate.swift:16)
20 libdispatch.dylib 0x204e8873 (Missing)
Any Thoughts on that why this happening.
Thanks in Advance!!
Update : - Code for AppDelegate.handleRemoteNotificationFromKilledState([NSObject : AnyObject])
func handleRemoteNotificationFromKilledState(userInfo:[NSObject : AnyObject]) {
var pushDict = userInfo[UIApplicationLaunchOptionsRemoteNotificationKey] as! Dictionary<NSObject,AnyObject>
let dict = pushDict["abc"] as? NSDictionary
if (dict?.valueForKey("alert") as? NSString) != nil {
let alert = dict?.valueForKey("alert") as! NSString
if let type=pushDict["NT"] as? NSString {
if type == "TO_ViewController_One" {
let qcid = pushDict["abcID"] as? String
self.notificationdictForkilled["qcid"] = qcid
self.notificationdictForkilled["ToViewController"] = "TO_ViewController_One"
} else if type == "TO_ViewController_Two" {
let qcid = pushDict["abcID"] as? String
self.notificationdictForkilled["qcid"] = qcid
self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Two"
} else if type == "TO_ViewController_Three" {
let qcid = pushDict["abcID"] as? String
self.notificationdictForkilled["qcid"] = qcid
self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Three"
} else if type == "TO_ViewController_Five" {
let qcid = pushDict["abcID"] as? String
self.notificationdictForkilled["qcid"] = qcid
self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Five"
} else if type == "TO_ViewController_Four" {
let qcid = pushDict["abcID"] as? String
self.notificationdictForkilled["qcid"] = qcid
self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Four"
} else if type == "TO_ViewController_Six" {
let qcid = pushDict["abcID"] as? String
self.notificationdictForkilled["qcid"] = qcid
self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Six"
} else if type == "TO_ViewController_Seven" {
let qcid = pushDict["abcID"] as? String
self.notificationdictForkilled["qcid"] = qcid
self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Seven"
} else if type == "TO_ViewController_Eight" {
let qcid = pushDict["abcID"] as? String
self.notificationdictForkilled["qcid"] = qcid
self.notificationdictForkilled["ToViewController"] = "TO_ViewController_Eight"
} else {
let qcid = userInfo["abcID"] as? String
self.notificationdictForkilled["qcid"] = qcid
self.notificationdictForkilled["ToViewController"] = type as String
}
self.viewstate = "Killed"
}
}
}
Related
When I try to fetch user data from Firebase a crash occurs for some users, I can't reproduce this crash myself but I do have the following crash log:
0 Ski Tracker 0x77bf0 closure #1 in HistoryPresenter.downloadHistory(completionHandler:) + 4340857840 (HistoryPresenter.swift:4340857840)
1 Ski Tracker 0x86c8 closure #1 in FetchFromDatabase.fetchUserHistoryFromDatabase(uid:completionHandler:) + 4340401864 (<compiler-generated>:4340401864)
2 Ski Tracker 0x8604 thunk for #escaping #callee_guaranteed (#guaranteed FIRDataSnapshot) -> () + 4340401668 (<compiler-generated>:4340401668)
3 FirebaseDatabase 0x1df28 __92-[FIRDatabaseQuery observeSingleEventOfType:andPreviousSiblingKeyWithBlock:withCancelBlock:]_block_invoke + 120
4 FirebaseDatabase 0xbf94 __43-[FChildEventRegistration fireEvent:queue:]_block_invoke.11 + 80
5 libdispatch.dylib 0x24b4 _dispatch_call_block_and_release + 32
6 libdispatch.dylib 0x3fdc _dispatch_client_callout + 20
7 libdispatch.dylib 0x127f4 _dispatch_main_queue_drain + 928
8 libdispatch.dylib 0x12444 _dispatch_main_queue_callback_4CF + 44
9 CoreFoundation 0x9a6f8 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
10 CoreFoundation 0x7c058 __CFRunLoopRun + 2036
11 CoreFoundation 0x80ed4 CFRunLoopRunSpecific + 612
12 GraphicsServices 0x1368 GSEventRunModal + 164
13 UIKitCore 0x3a23d0 -[UIApplication _run] + 888
14 UIKitCore 0x3a2034 UIApplicationMain + 340
15 libswiftUIKit.dylib 0x35308 UIApplicationMain(_:_:_:_:) + 104
16 Ski Tracker 0x7160 main + 4340396384 (FriendView.swift:4340396384)
17 ??? 0x1f6938960 (Missing)
If I understand the crash log correctly the code which is causing the crash is within the fetchUserHistoryFromDatabase function:
func fetchUserHistoryFromDatabase(uid : String, completionHandler: #escaping([String : Any]?) -> Void ) {
ref?.child("users").child(uid).child("runData").observeSingleEvent(of: .value, with: { snapshot in
guard let result = snapshot.value as? [String:Any] else {
print("Error no rundata")
completionHandler(nil)
return
}
completionHandler(result)
})
}
This function is called from downloadHistory where potential nil values are handled:
private func downloadHistory(completionHandler: #escaping () -> Void) {
if let id = Auth.auth().currentUser?.uid {
FetchFromDatabase().fetchUserHistoryFromDatabase(uid : id, completionHandler: { [weak self] dict in
if dict != nil {
for run in dict! {
self?.determineTimeStamp(run : run)
}
if !(self!.tempDict.isEmpty) {
let sortedDict = self?.tempDict.keys.sorted(by: { $0 > $1 } )
self?.convertDictToArray(sortedDict: sortedDict!)
}
}
completionHandler()
}
)}
}
Any help here is greatly appreciated.
Remove the force unwrapping from your code. Every ! is an invitation for a crash.
private func downloadHistory(completionHandler: #escaping () -> Void) {
if let id = Auth.auth().currentUser?.uid {
FetchFromDatabase().fetchUserHistoryFromDatabase(uid : id, completionHandler: { [weak self] dict in
guard let self = self else {
completion()
return
}
if let dict = dict {
for run in dict {
self.determineTimeStamp(run : run)
}
if !self.tempDict.isEmpty {
let sortedDict = self.tempDict.keys.sorted(by: { $0 > $1 } )
self.convertDictToArray(sortedDict: sortedDict)
}
}
completionHandler()
}
)}
}
I notice a self! there dangerous, because a user could leave the calling context of the function and since the closure has a capture list of weak self, it should return nil but you are forcing it
try this
private func downloadHistory(completionHandler: #escaping () -> Void) {
if let id = Auth.auth().currentUser?.uid {
FetchFromDatabase().fetchUserHistoryFromDatabase(uid : id, completionHandler: { [weak self] dict in
guard let self = self else { completionHandler()
return }
if let safeDict = dict {
for run in dict {
self.determineTimeStamp(run : run)
}
if (self.tempDict.isEmpty) {
let sortedDict = self.tempDict.keys.sorted(by: { $0 > $1 } )
self.convertDictToArray(sortedDict: sortedDict)
}
}
completionHandler()
}
)}
}
When I run my app, a function gets called in a view controller and when that happens I get signal SIGABRT.
How to solve this?
Function :
func setRootViewController()
{
if Auth.auth().currentUser != nil
{
let tabVC = storyboard?.instantiateViewController(withIdentifier: "TabVC") as! TestViewController
view.window?.rootViewController = tabVC
view.window?.makeKeyAndVisible()
}
else
{
let welcomeVC = storyboard?.instantiateViewController(withIdentifier: Constants.Storyboard.welcomeVC) as! ViewController
view.window?.rootViewController = welcomeVC
view.window?.makeKeyAndVisible()
}
}
When it crashes I get this in the console area :
21 CoreFoundation 0x00007fff23ac4241
CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17 22 CoreFoundation 0x00007fff23ac416c
__CFRunLoopDoSource0 + 76 23 CoreFoundation 0x00007fff23ac3944 __CFRunLoopDoSources0 + 180 24 CoreFoundation
0x00007fff23abe64f __CFRunLoopRun + 1263 25 CoreFoundation
0x00007fff23abde36 CFRunLoopRunSpecific + 438 26 GraphicsServices
0x00007fff37f64bb0 GSEventRunModal + 65 27 UIKitCore
0x00007fff46d562a3 UIApplicationMain + 1621 28 Do It !
0x000000010f1b654b main + 75 29 libdyld.dylib
0x00007fff51175cf5 start + 1 ) libc++abi.dylib: terminating with
uncaught exception of type NSException (lldb)
Try to avoid force unwraps. Try this:
func setRootViewController() {
if Auth.auth().currentUser != nil {
if let tabVC = storyboard?.instantiateViewController(withIdentifier: "TabVC") as? TestViewController {
view.window?.rootViewController = tabVC
view.window?.makeKeyAndVisible()
} else {
print("TabVC doesn't exist or is not a TestViewController")
}
} else {
let welcomeVC = storyboard?.instantiateViewController(withIdentifier: Constants.Storyboard.welcomeVC)
// you don't need to cast welcomeVC to a ViewController.
view.window?.rootViewController = welcomeVC
view.window?.makeKeyAndVisible()
}
}
Let me know if this helps or if you have any follow up questions.
I am trying to get data from multiple apis and saving it to my coredata database. Earlier it comes once in ten times. but now i am getting it every time.
I have created a DispatchGroup and trying to hit api one by one. Below is my code.
let group = DispatchGroup()
group.enter()
SharedFunctions.getCourseSessions {
print("Course Session Done")
group.leave()
}
group.enter()
SharedFunctions.getCourseContent {
print("Course Content Done")
group.leave()
}
group.enter()
SharedFunctions.getCourseQuiz {
print("Course Quiz Done")
group.leave()
}
group.notify(queue: DispatchQueue.global(qos: .background)) {
print("All async calls were run!")
DispatchQueue.main.async {
ACProgressHUD.shared.hideHUD()
completrion()
}
}
Below is my fetching and saving data from api
class func getCourseSessions(completion: #escaping () -> ()) {
let param = "module=getCourseSessions&userid=\(User.uId)&Akey=\(User.akey)&schedule_course_id=\(User.scheduleCourseId)"
SharedFunctions.callWebServices(url: URLS.Base_URL, methodName: "POST", parameters: param, istoken: false, tokenval: "", completion: { (jsonDict) in
print(jsonDict)
DispatchQueue.main.async {
if ((jsonDict.value(forKey: "message") as! NSDictionary).value(forKey: "success") as! String) == "true" {
SharedGlobalVariables.arrayCourseSessions = (((jsonDict.value(forKey: "message") as AnyObject).value(forKey: "data") as AnyObject).value(forKey: "result")) as! NSMutableArray
print(SharedGlobalVariables.arrayCourseSessions.count)
// DispatchQueue.main.async {
SharedGlobalVariables.LoginBool = true
// get a reference to the app delegate
if #available(iOS 10.0, *) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
print(SharedGlobalVariables.arrayCourseSessions.count)
for j in 0...SharedGlobalVariables.arrayCourseSessions.count - 1 {
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Course_Sessions", in: managedContext)
let courseSessionsScreen = Course_Sessions(entity: entity!, insertInto: managedContext)
if let arrData = SharedGlobalVariables.arrayCourseSessions[j] as? NSDictionary {
if let courseId = arrData.value(forKey: "course_id") as? Int16 {
courseSessionsScreen.course_id = courseId
}
if let userId = arrData.value(forKey: "user_id") as? Int16 {
courseSessionsScreen.user_id = userId
}
if let enableNextScreenSequence = arrData.value(forKey: "enable_nextscreen_sequence") as? Int16 {
courseSessionsScreen.enable_nextscreen_sequence = enableNextScreenSequence
}
}
do {
try managedContext.save()
// getCourseSessionProperties()
} catch let error as NSError {
print(error)
}
}
} else {
// Fallback on earlier versions
}
//}
}
completion()
}
})
}
There is no perticular place to crash app crash. it crash any where like above methode i am passing all apis.
Getting This error:
Error Domain=NSCocoaErrorDomain Code=132001 "(null)" UserInfo={message=attempt to recursively call -save: on the context aborted, stack trace=(
0 CoreData 0x0000000111ff3892 -[NSManagedObjectContext save:] + 306
1 Tuneem 0x000000010f64046c _TFFFZFC6Tuneem15SharedFunctions26getCourseSessionPropertiesFT10completionFT_T__T_U_FCSo12NSDictionaryT_U_FT_T_U_FT_T_ + 60
2 Tuneem 0x000000010f629197 _TTRXFo___XFdCb___ + 39
3 CoreData 0x000000011200cb52 developerSubmittedBlockToNSManagedObjectContextPerform + 178
4 libdispatch.dylib 0x000000011bf0205c _dispatch_client_callout + 8
5 libdispatch.dylib 0x000000011bee094f _dispatch_queue_serial_drain + 221
6 libdispatch.dylib 0x000000011bee1669 _dispatch_queue_invoke + 1084
7 libdispatch.dylib 0x000000011bee1b32 _dispatch_queue_override_invoke + 654
8 libdispatch.dylib 0x000000011bee3ec4 _dispatch_root_queue_drain + 634
9 libdispatch.dylib 0x000000011bee3bef _dispatch_worker_thread3 + 123
10 libsystem_pthread.dylib 0x000000011c299712 _pthread_wqthread + 1299
11 libsystem_pthread.dylib 0x000000011c2991ed start_wqthread + 13
)}
Error Domain=NSCocoaErrorDomain Code=132001 "(null)" UserInfo=. {message=attempt to recursively call -save: on the context aborted, stack trace=(
0 CoreData 0x0000000111ff3892 -[NSManagedObjectContext save:] + 306
1 Tuneem 0x000000010f64046c _TFFFZFC6Tuneem15SharedFunctions26getCourseSessionPropertiesFT10completionFT_T__T_U_FCSo12NSDictionaryT_U_FT_T_U_FT_T_ + 60
2 Tuneem 0x000000010f629197 _TTRXFo___XFdCb___ + 39
3 CoreData 0x000000011200cb52 developerSubmittedBlockToNSManagedObjectContextPerform + 178
4 libdispatch.dylib 0x000000011bf0205c _dispatch_client_callout + 8
5 libdispatch.dylib 0x000000011bee094f _dispatch_queue_serial_drain + 221
6 libdispatch.dylib 0x000000011bee1669 _dispatch_queue_invoke + 1084
7 libdispatch.dylib 0x000000011bee1b32 _dispatch_queue_override_invoke + 654
8 libdispatch.dylib 0x000000011bee3ec4 _dispatch_root_queue_drain + 634
9 libdispatch.dylib 0x000000011bee3bef _dispatch_worker_thread3 + 123
10 libsystem_pthread.dylib 0x000000011c299712 _pthread_wqthread + 1299
11 libsystem_pthread.dylib 0x000000011c2991ed start_wqthread + 13
)}
Trying to solve it from last couple of days getting no idea, any help will be appreciate.
Since we have renamed (Bestemming -> Place) the class and rewrote it from Objective-c to Swift some users experience crashes with it. We are trying to load an object from the NSUserDefaults with the NSCoding principle.
The crash:
Thread : Crashed: com.apple.main-thread
0 Flitsmeister 0x10018b720 specialized Place.init(coder : NSCoder) -> Place? (Place.swift)
1 Flitsmeister 0x10018a6f4 #objc Place.init(coder : NSCoder) -> Place? (Place.swift)
2 Foundation 0x1839ab92c _decodeObjectBinary + 2276
3 Foundation 0x1839aaf90 _decodeObject + 304
4 Foundation 0x1839aa124 +[NSKeyedUnarchiver unarchiveObjectWithData:] + 92
5 Flitsmeister 0x100103fa0 +[SharedUserDefaultsManager WorkPlace] (SharedUserDefaultsManager.m:72)
6 Flitsmeister 0x100090830 -[InvoerBestemmingTableViewController viewWillAppear:] (InvoerBestemmingTableViewController.m:106)
7 UIKit 0x187d8074c -[UIViewController _setViewAppearState:isAnimating:] + 628
8 UIKit 0x187d804c0 -[UIViewController __viewWillAppear:] + 156
9 UIKit 0x187e27130 -[UINavigationController _startTransition:fromViewController:toViewController:] + 760
10 UIKit 0x187e26a6c -[UINavigationController _startDeferredTransitionIfNeeded:] + 868
11 UIKit 0x187e26694 -[UINavigationController __viewWillLayoutSubviews] + 60
12 UIKit 0x187e265fc -[UILayoutContainerView layoutSubviews] + 208
13 UIKit 0x187d63778 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 656
14 QuartzCore 0x185772b2c -[CALayer layoutSublayers] + 148
15 QuartzCore 0x18576d738 CA::Layer::layout_if_needed(CA::Transaction*) + 292
16 QuartzCore 0x18576d5f8 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 32
17 QuartzCore 0x18576cc94 CA::Context::commit_transaction(CA::Transaction*) + 252
18 QuartzCore 0x18576c9dc CA::Transaction::commit() + 512
19 UIKit 0x187d59c78 _afterCACommitHandler + 180
20 CoreFoundation 0x18302c588 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
21 CoreFoundation 0x18302a32c __CFRunLoopDoObservers + 372
The class:
#objc(Place)
class Place : NSObject, NSCoding, CustomDebugStringConvertible
{
let name: String
let location: CLLocation
var lastUsed: NSDate?
var type: PlaceType
var address: String?
//MARK: - NSCoding protocol
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(address, forKey: "address")
aCoder.encodeInt(type.rawValue, forKey: "type")
aCoder.encodeObject(location, forKey: "location")
aCoder.encodeObject(lastUsed, forKey: "lastUsed")
}
required init?(coder aDecoder: NSCoder) {
if let locatieNaam : String = aDecoder.decodeObjectForKey("locatieNaam") as? String {
//This is the OLD object
name = locatieNaam
let nullableLocation : CLLocation? = aDecoder.decodeObjectForKey("locatie") as? CLLocation
if let notnulllablelocation : CLLocation = nullableLocation {
location = notnulllablelocation
} else {
location = CLLocation.init(latitude: 0, longitude: 0) //Not possible
}
lastUsed = aDecoder.decodeObjectForKey("lastUsed") as? NSDate
if aDecoder.decodeBoolForKey("isThuis") {
type = .Home
} else if aDecoder.decodeBoolForKey("isWerk") {
type = .Work
} else if aDecoder.decodeBoolForKey("isFavoriet") {
type = .Favoriet
} else {
type = .Other
}
address = nil
}
else {
name = aDecoder.decodeObjectForKey("name") as! String
let nullableLocation : CLLocation? = aDecoder.decodeObjectForKey("location") as? CLLocation
if let notnullableLocation : CLLocation = nullableLocation {
location = notnullableLocation
} else {
location = CLLocation.init(latitude: 0, longitude: 0) //Not possible
}
lastUsed = aDecoder.decodeObjectForKey("lastUsed") as? NSDate
type = PlaceType.init(rawValue: aDecoder.decodeInt32ForKey("type"))!
address = aDecoder.decodeObjectForKey("address") as? String
}
}
}
Reading from NSUserDefaults:
+ (Place*)WorkPlace;
{
#try {
NSUserDefaults *mySharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:kSharedUserDefaults];
NSData *result = [mySharedDefaults objectForKey:kWerkBestemming];
if(result == NULL)
return nil;
[NSKeyedUnarchiver setClass:[Place class] forClassName:#"Bestemming"];
[NSKeyedUnarchiver setClass:[Place class] forClassName:#"BestemmingBase"];
Place *place = [NSKeyedUnarchiver unarchiveObjectWithData:result];
if(place != nil) {
place.type = PlaceTypeWork; //Needed because the old Bestemming class didnt saved the boolean isWerk
}
return place;
}
#catch (NSException *exception) {
return nil;
}
}
The crash log says it crashes on line 0, which is comment so I think it crashes in the init method and I think it has something to do with an object which is null but could not be null.
What i've tried:
Try catch in SharedUserDefaultsManager
Extra checks on non-nullables
For those users where the app crashes I can live with removing the object from NSUserDefaults. Only if I can know when it happens.
Think this is a much better approach to deal with the NSCoding init method and return nil if variables are not what you are expecting:
required convenience init?(coder decoder: NSCoder) {
guard let title = decoder.decodeObjectForKey("title") as? String,
let author = decoder.decodeObjectForKey("author") as? String,
let categories = decoder.decodeObjectForKey("categories") as? [String]
else { return nil }
self.init(
title: title,
author: author,
pageCount: decoder.decodeIntegerForKey("pageCount"),
categories: categories,
available: decoder.decodeBoolForKey("available")
)
}
From NSHipster: http://nshipster.com/nscoding/
Now let's see how the new version is working out.
Edit: it worked!
This question already has answers here:
Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?
(79 answers)
Closed 7 years ago.
Program starts up and then an error is thrown and it brings me to the appDelegate.swift file --class AppDelegate: UIResponder, UIApplicationDelegate { -- thread 1:signal sigabort
Here is the code:
import UIKit
class ViewController: UIViewController {
let filemgr = NSFileManager.defaultManager()
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
#IBOutlet weak var address: UITextField!
#IBOutlet weak var street: UITextField!
#IBOutlet weak var city: UITextField!
#IBOutlet weak var state: UITextField!
#IBOutlet weak var zip: UITextField!
#IBOutlet weak var status: UILabel!
var database = NSString() // <-- CRASHING HERE
override func viewDidLoad() {
super.viewDidLoad()
let docsDir = dirPaths[0]
let databasePath = docsDir.stringByAppendingString("/contacts.db") // This seems to work
if !filemgr.fileExistsAtPath(databasePath as String) {
let contactDB = FMDatabase(path: databasePath as String)
if contactDB == nil {
print("Error DB")
}
if contactDB.open() {
let sql = "CREATE TABLE IF NOT EXISTS Houses (ID INTEGER PRIMARY KEY AUTOINCREMENT, Address TEXT, Street TEXT, City TEXT, State TEXT, Zip TEXT)"
if !contactDB.executeStatements(sql) {
print("Error DB")
}
else {
print("Error DB")
}
}
}
}
#IBAction func saveData(sender: AnyObject) {
let docsDir = dirPaths[0]
let databasePath = docsDir.stringByAppendingString("/contacts.db") // This seems to work
if !filemgr.fileExistsAtPath(databasePath as String) {
let contactDB = FMDatabase(path: databasePath as String)
if contactDB.open() {
let sql = "insert into Houses (Address, State, City, State, Zip) values ('\(address),\(street),\(city),\(state),\(zip))"
let result = contactDB.executeUpdate(sql, withArgumentsInArray: nil)
if !result {
status.text = "Failed to add house"
print("DB Error")
}
else {
status.text = "Added House"
address.text = ""
street.text = ""
city.text = ""
state.text = ""
zip.text = ""
}
}
else {
print("DB Error")
}
}
}
#IBAction func findContact(sender: AnyObject) {
let docsDir = dirPaths[0]
let databasePath = docsDir.stringByAppendingString("/contacts.db")
if !filemgr.fileExistsAtPath(databasePath as String) {
let contactDB = FMDatabase(path: databasePath as String)
if contactDB.open() {
let sql = "SELECT address, street, state, state, zip WHERE ID = 1" // Change this later
let results:FMResultSet? = contactDB.executeQuery(sql,withArgumentsInArray: nil)
if results?.next() == true {
address.text = results?.stringForColumn("Address")
street.text = results?.stringForColumn("Street")
city.text = results?.stringForColumn("City")
state.text = results?.stringForColumn("State")
zip.text = results?.stringForColumn("Zip")
}
else {
status.text = "Record not found"
address.text = ""
street.text = ""
city.text = ""
state.text = ""
zip.text = ""
}
contactDB.close()
}
else {
print("DBError")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here are the errors:
2015-11-10 00:34:33.385 SQLiteDatabaseExample[3656:218507] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'
*** First throw call stack:
(
0 CoreFoundation 0x0000000106aa8f45 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x0000000106522deb objc_exception_throw + 48
2 CoreFoundation 0x0000000106aa8b89 -[NSException raise] + 9
3 Foundation 0x000000010488fa6b -[NSObject(NSKeyValueCoding) setValue:forKey:] + 288
4 UIKit 0x0000000104e6e04c -[UIViewController setValue:forKey:] + 88
5 UIKit 0x000000010509ba71 -[UIRuntimeOutletConnection connect] + 109
6 CoreFoundation 0x00000001069e9a80 -[NSArray makeObjectsPerformSelector:] + 224
7 UIKit 0x000000010509a454 -[UINib instantiateWithOwner:options:] + 1864
8 UIKit 0x0000000104e74c16 -[UIViewController _loadViewFromNibNamed:bundle:] + 381
9 UIKit 0x0000000104e75542 -[UIViewController loadView] + 178
10 UIKit 0x0000000104e758a0 -[UIViewController loadViewIfRequired] + 138
11 UIKit 0x0000000104e76013 -[UIViewController view] + 27
12 UIKit 0x0000000104d4f51c -[UIWindow addRootViewControllerViewIfPossible] + 61
13 UIKit 0x0000000104d4fc05 -[UIWindow _setHidden:forced:] + 282
14 UIKit 0x0000000104d614a5 -[UIWindow makeKeyAndVisible] + 42
15 UIKit 0x0000000104cdb396 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4131
16 UIKit 0x0000000104ce19c3 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1750
17 UIKit 0x0000000104cdeba3 -[UIApplication workspaceDidEndTransaction:] + 188
18 FrontBoardServices 0x0000000108776784 -[FBSSerialQueue _performNext] + 192
19 FrontBoardServices 0x0000000108776af2 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
20 CoreFoundation 0x00000001069d5011 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
21 CoreFoundation 0x00000001069caf3c __CFRunLoopDoSources0 + 556
22 CoreFoundation 0x00000001069ca3f3 __CFRunLoopRun + 867
23 CoreFoundation 0x00000001069c9e08 CFRunLoopRunSpecific + 488
24 UIKit 0x0000000104cde4f5 -[UIApplication _run] + 402
25 UIKit 0x0000000104ce330d UIApplicationMain + 171
26 SQLiteDatabaseExample 0x00000001047a05ad main + 109
27 libdyld.dylib 0x000000010824f92d start + 1
28 ??? 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
Check your ViewController's IBOutlets connections and remove any unwanted connection.It can happen when you delete the outlet code in your class.