1290 1290 - 1 year ago 158
iOS Question

unexpectedly found nil while unwrapping an Optional value keyboardWillShow

I have this code below which runs when the keyboardWillShowNotification is called:

func keyboardWillShow(_ notification: Notification) {
keyboard = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
animaton = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue

UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.scrollView.frame.size.height = self.scrollViewHeight - self.keyboard.height

I am getting an error on the second line saying:
unexpectedly found nil while unwrapping an Optional value
. Basically whenever I click on one of the textFields this notification for the keyboard will be called and the code in
will run. I know I put
statements but I want to know why I am getting nil for this.

I am not sure how I am getting this error or how to debug it either. Is it because I am running it from the simulator?

Here is what printing the notification.userInfo gives:

Optional([AnyHashable("UIKeyboardFrameEndUserInfoKey"): NSRect: {{0, 315}, {320, 253}}, AnyHashable("UIKeyboardIsLocalUserInfoKey"): 1, AnyHashable("UIKeyboardBoundsUserInfoKey"): NSRect: {{0, 0}, {320, 253}}, AnyHashable("UIKeyboardAnimationCurveUserInfoKey"): 7, AnyHashable("UIKeyboardCenterBeginUserInfoKey"): NSPoint: {160, 694.5}, AnyHashable("UIKeyboardCenterEndUserInfoKey"): NSPoint: {160, 441.5}, AnyHashable("UIKeyboardFrameBeginUserInfoKey"): NSRect: {{0, 568}, {320, 253}}, AnyHashable("UIKeyboardAnimationDurationUserInfoKey"): 0.25])

Answer Source

From the docs:

let UIKeyboardFrameEndUserInfoKey: String 


The key for an NSValue object containing a CGRect that identifies the end frame of the keyboard in screen coordinates

Your second key:

let UIKeyboardAnimationDurationUserInfoKey: String

Description The key for an NSNumber object containing a double that identifies the duration of the animation in seconds.

So you need to cast the first one to NSValue and the second one to NSNumber:

func keyboardWillShow(_ notification: Notification) {
    guard let userInfo = notification.userInfo else { return }
    keyboard = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
    animaton = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    // your code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download