Aleem Cummins
Aleem Cummins

Reputation: 13

How can I able to act upon the APNS push message by taking an action contained in the payload

I am new to objective-c, xcode and app dev so please bear this in mind.

I can send a push notification via APNS to my emerging app. I can see the JSON message and can NSSLog it.

Payload: {
    aps = {
        alert = {
            "action-loc-key" = Reveal;
            body = "Hi Aleem, we have a new special offer just for you!";
        };
        badge = 70;
        sound = default;
    };

    myCMD = {
        "update_colour" = red;
    };
}

All good so far. However, I need to be able to act upon the push message by taking an action. For example, I want to be able to extract the update_colour and use the value red to change the background colour of a label on my one and only controller to red.

My problem is that I cannot reference my label from my appdelegate.m. Therefore I can't update the background colour or even call a method on the controller to do it either.

Any help with this would be really appreciated.

Upvotes: 1

Views: 518

Answers (1)

SlateEntropy
SlateEntropy

Reputation: 4018

In your delegate add:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;

Then when a push notification is received whilst the application is running/ a user opens a push notification you can access the notifications payload and act upon it, you could then send a notification to your view controller.

Add the Observer, in your view:

[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(backgroundChanged:)
                                         name:@"ChangeBackground"
                                       object:nil];

Add handle it.

- (void)backgroundChanged:(NSNotification *)notification {
    NSDictionary *dict = [notification userInfo];

    NSLog(@"%@" [[dict valueForKey:@"myCMD"] valueForKey:@"background-colour"]);

    label.backgroundColor = [UIColor xxx];
}

Then in the delegate:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    if([userInfo valueForKey:@"myCMD"]) {
            NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
        [notificationCenter postNotificationName:@"ChangeBackground"
                                    object:nil
                                    userInfo:userInfo];
    }
}

Upvotes: 1

Related Questions