Using Custom Data

This guide will help you to better understand how to pass custom data to your apps in the push notification payload so your app could react to such pushes and perform various actions accordingly.

The ways you handle custom data can vary according to your business objectives. In this article we’ll show some basic examples of parsing custom data and performing simple actions:

  • changing the background color of the app;
  • opening a custom page in your app.

Prerequisites

This guide covers iOS Native development. You can find the source code example for this guide in our GitHub repo. It is assumed that you have iOS sample application configured and receiving push notifications as per Native iOS Integration Guide.

For our guide we will use the app with single View Controller.

In AppDelegate in didFinishLaunchingWithOptions function we will use self.viewController as a delegate for push notifications processing:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
 //some code
 
    //-----------PUSHWOOSH PART-----------
    // set custom delegate for push handling, in our case - view controller
	PushNotificationManager.push().delegate = self.viewController
  
  // handling push on app start
  PushNotificationManager.push().handlePushReceived(launchOptions)
  
  // make sure we count app open in Pushwoosh stats
  PushNotificationManager.push().sendAppOpen()
  
  // register for push notifications!
  PushNotificationManager.push().registerForPushNotifications()
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     
    //some code
  
    //-----------PUSHWOOSH PART-----------
    // set custom delegate for push handling, in our case - view controller
    [PushNotificationManager pushManager].delegate = self.viewController;
     
    // handling push on app start
    [[PushNotificationManager pushManager] handlePushReceived:launchOptions];
     
    // make sure we count app open in Pushwoosh stats
    [[PushNotificationManager pushManager] sendAppOpen];
     
    // register for push notifications!
    [[PushNotificationManager pushManager] registerForPushNotifications];
}

Our ViewController implements the PushNotificationDelegate protocol:

class ViewController: UIViewController, PushNotificationDelegate
@interface ViewController : UIViewController <UITextFieldDelegate, PushNotificationDelegate>

And therefore has onPushAccepted function that handles received push notifications:

//user pressed on the push notification
func onPushAccepted(_ pushManager: PushNotificationManager!, withNotification pushNotification: [AnyHashable : Any]!, onStart: Bool) {
//user pressed on the push notification
- (void) onPushAccepted:(PushNotificationManager *)pushManager withNotification:(NSDictionary *)pushNotification {

Retrieving data from push payload

In order to process custom data from the push notification payload we would obviously need to extract it from the push payload first. To achieve that you have to call the following function:

let jsonData = PushNotificationManager.push().getCustomPushData(asNSDict: pushNotification)
NSString *jsonData = [pushManager getCustomPushDataAsNSDict:pushNotification];

Changing the view background color

Now that we have our custom data extracted from the push payload, let’s do something with it. For instance, let’s change the view background color. We assume that custom data would contain “r”, “g”, “b” items in JSON object format as follows:

let redStr = jsonData["r"]
let greenStr = jsonData["g"]
let blueStr = jsonData["b"]

if (redStr != nil && greenStr != nil && blueStr != nil) {
	self.setViewBackgroundColor(red: redStr!, green: greenStr!, blue: blueStr!)
}
NSString *redStr = [jsonData objectForKey:@"r"];
NSString *greenStr = [jsonData objectForKey:@"g"];
NSString *blueStr = [jsonData objectForKey:@"b"];
 
if (redStr && greenStr && blueStr) {
    [self setViewBackgroundColorWithRed:redStr green:greenStr blue:blueStr];
}

We will use the following function to set background color:

    func setViewBackgroundColor(red: String, green: String, blue: String) {
        let red = CGFloat((red as NSString).floatValue)
        let green = CGFloat((green as NSString).floatValue)
        let blue = CGFloat((blue as NSString).floatValue)
        
        let color = UIColor(red: red, green: green, blue: blue, alpha: 1)
        
        UIView.animate(withDuration: 0.3) {
            self.view.backgroundColor = color
            self.presentedViewController?.view.backgroundColor = color
        }
    }
- (void)setViewBackgroundColorWithRed:(NSString *)redString green:(NSString *)greenString blue:(NSString *)blueString {
    CGFloat red = [redString floatValue] / 255.0f;
    CGFloat green = [greenString floatValue] / 255.0f;
    CGFloat blue = [blueString floatValue] / 255.0f;
     
    UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
    [UIView animateWithDuration:0.3 animations:^{
        self.view.backgroundColor = color;
        self.presentedViewController.view.backgroundColor = color;
    }];
}

Let’s test our example. Go to the app and enter any push notification text:

Then switch to the Action tab. As we've decided that our custom data format would be JSON object with “r”, “g”, “b” values in it, we need to use “custom data” field in the Control Panel and populate it with JSON object {"r":30, "g":144, "b":255}:

This should set the background color to dodger blue. Now scroll down and press “Woosh”!

Push notification received!

And the screen turns dodger blue:

Opening a custom page

Let’s try something different like opening custom page of the app! Assume that we have special discount page in our app where user can redeem the voucher received in push notification.

As most of the view controllers require additional initialization and cannot be presented out of the box from push notification, some additional coding is required here.

But first let’s start with a simple new view controller. We’ll call it CustomPageViewController. Please refer to the CustomPageViewController.xib in the sample project for the controls layout. Our new controller will have label, a close button and two properties to initialize bgColor and discount.

class CustomPageViewController: UIViewController {
    
    var bgColor: UIColor?
    
    var discount: Int?
    
    @IBOutlet weak var titleLabel: UILabel?
    
        override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = self.bgColor
        
        if self.discount != nil {
            self.titleLabel?.text = "Only today get \(self.discount!)% discount!"
        }
    }
    
    @IBAction func closeAction(sender: UIButton) {
        self.dismiss(animated: true, completion: nil)
    }
    
}
@interface CustomPageViewController : UIViewController
 
@property (nonatomic, strong) UIColor *bgColor;
@property (nonatomic, assign) NSInteger discount;
 
@property (nonatomic, weak) IBOutlet UILabel *titleLabel;
 
@end
  
@implementation CustomPageViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = self.bgColor;
    self.titleLabel.text = [NSString stringWithFormat:@"Only today get %ld%% discount!", (long)self.discount];
}
 
- (IBAction)closeAction:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
 
@end

Let’s get back to our push notifications handling function.

We assume that the discount value will come as "d" parameter in JSON of the push notifications payload. As push notification payload is limited in size you’d rather use short names for the parameters.

let discount = jsonData["d"]
        
if discount != nil {
		self.showPromoPage(discount: discount!)
}
NSString *discount = [jsonData objectForKey:@"d"];
 
if (discount) {
    [self showPromoPage:discount];
}

And showPromoPage function:

func showPromoPage(discount: String) {
		let vc = CustomPageViewController()
		vc.bgColor = self.view.backgroundColor
		vc.discount = Int(discount)
		vc.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
    
   	if self.presentedViewController != nil {
    		self.dismiss(animated: true, completion: {
        		self.present(vc, animated: true, completion: nil)
        })
 		} else {
    		self.present(vc, animated: true, completion: nil)
    }
}
- (void)showPromoPage:(NSString *)discount {
    CustomPageViewController *vc = [[CustomPageViewController alloc] init];
    vc.bgColor = self.view.backgroundColor;
    vc.discount = [discount integerValue];
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
     
    if (self.presentedViewController) {
        [self dismissViewControllerAnimated:YES completion:^{
            [self presentViewController:vc animated:YES completion:nil];
        }];
    } else {
        [self presentViewController:vc animated:YES completion:nil];
    }
}

Now go back to the Control Panel and add "d" key and its value to the custom data, and press Woosh!

Open the app from this push, and it’ll display the page with a discount:

You can write code to initialize and open different View Controllers depending on the parameters you pass in push notifications payload.

Using Custom Data