Search code examples
iosswiftexceptionkeychain

Issue with Exception manage in iOS Swift


Hello

I would like to ask you about a problem with exception manage in a code in IOS using Swift 2.0 language.

I have the following code:

alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
     // Remove save value in Keychain
     let MyKeychainWrapper = KeychainWrapper()
     MyKeychainWrapper.setValue("Account", forKey: kSecAttrAccount as String)
     MyKeychainWrapper.setValue("password", forKey: kSecValueData as String)
     let loginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("loginViewController") as! LoginViewController

     self.presentViewController(loginViewController, animated: true, completion: nil)
}))

The problem is that I'm getting the following exception in this code:

2015-10-26 08:04:49.464 RapidSentryMaster[1907:25789] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<KeychainWrapper 0x7fe783922820> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key v_Data.'

I supposed that the exception is due because don't find any KeyChain saved previously, so I tried to managed the exception in the same way that i used to do for example in android or other languages using try..catch

alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
     // Remove save value in Keychain
     do{
         let MyKeychainWrapper = KeychainWrapper()
         try MyKeychainWrapper.setValue("Account", forKey: kSecAttrAccount as String)
         try MyKeychainWrapper.setValue("password", forKey: kSecValueData as String)
     }catch{

     }
     let loginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("loginViewController") as! LoginViewController
     self.presentViewController(loginViewController, animated: true, completion: nil)
 }))

Doing that i got the following problem:

No calls to throwing functions occur within try expression and catch block is unreachable...

I would like to ask you, what is the correct way to manage an exception like this?

Thanks in advanced


Solution

  • Look at KeychainWrapper.h file. There is no method setValue:forKey:
    Instead you should use mySetObject:forKey:
    If you want try this tutorial.
    Cheers.