Skip to content

How to display messages when app is running in the foreground?

Olga Koroleva edited this page Dec 13, 2016 · 22 revisions

In order to display incoming messages (both pushed by APNs and pulled from the server) while your application is running in the foreground, you have to:

  1. Subscribe to MMNotificationMessageReceived notification:

    //Objective-C
    [[NSNotificationCenter defaultCenter] addObserver: self
                                             selector: @selector(handleNewMessageReceivedNotification:)
                                                 name: MMNotificationMessageReceived
                                               object: nil];
    //Swift
    NotificationCenter.default.addObserver(self,
    										selector: #selector(self.handleNewMessageReceivedNotification(_:)),
    										name: NSNotification.Name(rawValue:  MMNotificationMessageReceived),
    										object: nil)
  2. Handle the notifications:

    //Objective-C
    -(void)handleNewMessageReceivedNotification:(NSNotification *)notification {
    	// Display the message only if the application is in the foreground
    	if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
    		id messagePayload = notification.userInfo[MMNotificationKeyMessage];
    		if ([messagePayload isKindOfClass:[MTMessage class]]) {
    			MTMessage * message = messagePayload;
    		
    			// here comes your custom UI, i.e. standard UIAlertController:
    			UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"New message" message:message.text preferredStyle:UIAlertControllerStyleAlert];
    			[alertController addAction: [UIAlertAction actionWithTitle:@"Dismiss" style:UIAlertActionStyleCancel handler:nil]];
    			UIViewController * presentingVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    			[presentingVC presentViewController:alertController animated:YES completion:nil];
    		}
    	}
    }

	```swift
	//Swift
	@objc func handleNewMessageReceivedNotification(_ notification: NSNotification) {
		// Only display the message if the application is in the foreground
		guard UIApplication.shared.applicationState == .active,
			let userInfo = notification.userInfo,
			let message = userInfo[MMNotificationKeyMessage] as? MTMessage
		else {
			return
		}
		
		// here comes your custom UI, i.e. standard UIAlertController:
		let alertController = UIAlertController(title: "New message", message: message.text, preferredStyle: .alert)
		alertController.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
		if let presentingVC = UIApplication.shared.keyWindow?.rootViewController {
			presentingVC.present(alertController, animated: true, completion: nil)
		}
	}
	```
Clone this wiki locally