Is there a way for me to respond to an APNS push notification by executing a task specified in the payload?

As a newcomer to objective-c, xcode, and app development, I kindly ask for your patience.

I have managed to send a push notification via APNS to my new app. I can view the JSON message and log it using NSSLog.

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;
    };
}

Everything seems to be working well so far. However, I am struggling to take action based on the received push message. For instance, I would like to extract the update_colour value (red in this case) and change the background color of a label in my controller to red.

The issue lies in my inability to reference the label from my appdelegate.m file. Consequently, I cannot update the background color or call a method on the controller to do so either.

Any assistance with this matter would be greatly valued.

Answer №1

To implement handling push notifications in your app, make sure to include the following code in your delegate:

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

When a push notification is received while the app is active or when a user interacts with a push notification, you can access the payload of the notification and perform actions based on it. You can then send a notification to your view controller.

In your view controller, add an Observer:

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

Add the method to handle the notification:

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

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

    label.backgroundColor = [UIColor xxx];
}

Then, in your delegate, implement the method for receiving remote notifications:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

VUE 3 inexplicably failing to display the custom component's template, console remains error-free

I am utilizing flask, html, js for building a web application. I am currently facing an issue where the template defined in the component <add-movie> within movies.js is not being rendered into add_movies.html. The add_movies.html extends base_admin ...

how to protect your javascript and php code

I have a question about "injection", specifically javascript injection which I find confusing. Suppose I have a javascript function that sends an AJAX request to get a user's permission level, and then uses an if statement to assign power based on th ...

Boost the elements' worth within an array

Assume I am working with an array shown below... let myArr = [0,0,2,0,0]; I am aiming to generate a ripple effect where the modified array becomes [0,1,2,1,0] ...

(Vue) Troubleshooting text display issues on an iPad

This issue is specific to the IPad Pro 6th Generation and occurs only under certain circumstances (such as during the initial app launch). You can see a screenshot of the error here. The original text in Korean has caused the error as shown in the image. ...

Retrieving data from the <script> tag and transferring it to the t-esc tag within Odoo 12

After attempting to retrieve the current coordinates of a location in Odoo, I successfully obtained longitude and latitude data through an alert generated by the following code: <button onclick="getLocation()">Try It</button> ...

Top method for showcasing animated images (HTML/CSS/JS)

For my website, I want to create an engaging animation showing a coin being flipped multiple times in the air before landing on a specific side. After the animation finishes, I would like it to transform into a static image of the final result. I've ...

Obtaining an element in the Document Object Model (DOM) following

There are numerous questions and answers regarding this issue, but I am struggling to adapt it to my specific case. My extension fetches positions (1,2,...100) on the scores pages of a game. Upon initial page load, I receive the first 100 positions. Howev ...

Executing a function defined in a .ts file within HTML through a <script> tag

I am attempting to invoke a doThis() function from my HTML after it has been dynamically generated using a <script>. Since the script is loaded from an external URL, I need to include it using a variable in my .ts file. The script executes successfu ...

Using Django's template filters within a JavaScript script to manipulate an object's attribute

I am facing an issue where django's template filters are not working inside a js script when applied to an object's attribute. When I use the following code, it results in a js SyntaxError: <script> {{ obj.geometry.geojson | safe }} & ...

Tips for encoding ParsedUrlQuery into a URL-friendly format

Switching from vanilla React to NextJS has brought about some changes for me. In the past, I used to access my URL query parameters (the segment after the ? in the URL) using the useSearchParams hook provided by react-router, which returned a URLSearchPara ...

Getting the value of an element using a string in JQuery

How can I achieve the following using JQuery? var test = "'#ISP'"; alert($(test).val()); I am receiving a "Syntax error, unrecognized expression." I believe I might be overlooking something here. Thank you in advance! ...

Update the SQL database by transferring star ratings from a JSP file

Utilizing JSP to showcase information obtained from user queries, I have implemented a system where contextual data and the query itself are saved in a MySQL database using JDBC each time a new query is input. To enhance user interaction, I wanted to incor ...

Is there any difference in loading speed when using an async function in the createConnection method of promise-mysql?

Is it more efficient to use asynchronous createConnection or not? Does this impact the loading speed in any way? I am working with express, ReactJS, and promise-mysql. Which approach is preferable? Option 1: async connect () { try{ ...

Preventing the copying and pasting of HTML ruby tags

I am currently using ruby tags to include pinyin in my text. For instance: <p> <ruby>与<rt>yǔ</rt></ruby><ruby>摩<rt>mó</rt></ruby><ruby>拜<rt>bài</rt></ruby><ruby& ...

Engaging JavaScript Navigation

I am looking to create an interactive JavaScript menu or image map where users can press down, highlight, and hit enter on four different items to reveal hidden messages. However, I struggle with JavaScript and could really use some assistance. I have alr ...

Flask API does not recognize elif and else conditions

Creating a flask API that deals with various nested JSON files presents an interesting challenge. Depending on the data within these files, different actions need to be taken. The sorting logic is based on conditional statements as shown below: if (jsonFi ...

Troubleshooting ER_BAD_FIELD_ERROR in a node mysql stored procedure

Encountering an error message while executing the following code: Error: ER_BAD_FIELD_ERROR: Unknown column 'employee_id' in 'field list' Output: { employee_id: '6', employee_name: 'test', employee_contact: ...

Unveiling an HTML file using the express.static middleware on Replit

When using Replit to render an HTML file with res.sendFile within an app.get function, everything works smoothly. I can include logos, styles, and JavaScript logic files by utilizing the express.static middleware. However, if I attempt to also make the HTM ...

Using JavaScript to make an asynchronous call to the server via AJAX

Is it true that clients can block JavaScript in their browsers? If so, what impact does it have on AJAX calls - do they still function properly? ...

Handling Asynchronous API Requests with AngularJS

I am facing an issue with displaying data from API in my files foo.js and foo.html. While fetching information asynchronously in foo.js, I store it in an object that should be accessible in foo.html. However, despite receiving the data correctly, I am una ...