eric.mitchell
eric.mitchell

Reputation: 8845

applicationWillResignActive dismiss keyboard iPhone

When an SMS is received during the use of my app, I would like for any open keyboards to be dismissed. How can I do that from applicationWillResignActive in my app delegate?

Upvotes: 0

Views: 872

Answers (2)

Rusiru Boteju
Rusiru Boteju

Reputation: 121

For a Swift 5 implementation try this

override func viewDidLoad() {
    super.viewDidLoad()
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
}

@objc func appMovedToBackground() {
    print("App moved to background!")
}

For more information please follow https://www.hackingwithswift.com/example-code/system/how-to-detect-when-your-app-moves-to-the-background

Upvotes: 0

jluckyiv
jluckyiv

Reputation: 3691

Implement code like the example in this answer. Have your view controllers register for UIApplicationWillResignActiveNotification. When the notification fires, call resignFirstResponder. That way you avoid tight coupling between your UIApplicationDelegate and your view controller. Assuming your view controller has a UITextField named textField:

- (void) applicationWillResign {
    [self.textField resignFirstResponder];
}

- (void) viewDidLoad { 
    [[NSNotificationCenter defaultCenter]
        addObserver:self
        selector:@selector(applicationWillResign)
        name:UIApplicationWillResignActiveNotification 
        object:NULL];
}

Upvotes: 4

Related Questions