SEND PUSH NOTIFICATIONS TO AN IOS APP WITH PYTHON AND AWS LAMBDA

SEND PUSH NOTIFICATIONS TO AN IOS APP WITH PYTHON AND AWS LAMBDA

<strong>Originally published <em>at</em></strong><em>&nbsp;</em><a href="https://pusher.com/tutorials/push-notifications-ios-python-aws-lambda" target="_blank">pusher.com</a>

Pusher Beams allows you to customize push notifications you send to your devices via a server. However it can be expensive to run a server 24 hours a day 7 days a week and we may only need to send notifications every so often. This is where AWS Lambda can help. Lambda functions are serverless and work on a pay as you go model (with a generous free tier). This means that you only pay for when you use the function. We’re going to explore how we can setup Pusher Beams on an iOS client using an AWS Lambda function running Python to trigger the notifications.

Prerequisites
  • A free AWS account. You can create one here.
  • A free Pusher account. You can create one here.
  • Python 3.7.x installed on your local machine. Download here.
  • Xcode 10+
  • MacOS
  • An iOS device for testing notifications.
  • An understanding of iOS development and Xcode environment.
  • Cocoapods - Install instructions here.

You will also need to have pip installed for installing Python dependencies. Run the following commands in a terminal:

    $ sudo easy_install pip3
    $ brew install pipenv

Create your Lambda function

Creating a Pusher Beams instance

Login or create an account to access your dashboard here. Create a new Pusher Beams instance using the dashboard.

Complete step one of the iOS setup guide, by providing your APNS key and team ID and clicking Continue. We will pick up the remainder later on in this tutorial. Press the X to exit the setup guide and you will be returned to your dashboard for that instance. Scroll to the bottom of the page and you will find your Pusher Beams instance ID and secret key, make note of these you will need them later.

Writing our function

We will need to install our packages and write our function on our local machine before we can upload it to a Lambda function. Create a new working directory on your local machine and within run the following command in your terminal working directory:

    $ pipenv install pusher_push_notifications
    $ pipenv install requests

These commands will install our Pusher notifications dependency within our local directory. It also sets up a virtual environment for our project. Next create a new file called index.py and open it in your favorite text editor and add the following code:

    // index.py
    from pusher_push_notifications import PushNotifications
    import requests

    def lambda_handler(event, context):
        beams_client = PushNotifications(
                    instance_id='YOUR_INSTANCE_ID',
                    secret_key='YOUR_SECRET_KEY',
                    )

        response = beams_client.publish_to_interests(interests=['hello'],
                                                 publish_body={
                                                 'apns': {
                                                    'aps': {
                                                        'alert': {
                                                            'title': event['title'],
                                                            'body': event['message']
                                                            },
                                                        },
                                                    },
                                                 },
                                                 )
        print(response['publishId'])

This code will be used by our Lambda function later on to publish notifications to devices that are registered for the hello interest. We use the event['title'] and event['message'] to form part of the message. We’ll look at this in more detail when we come to test our integration. Remember to replace YOUR_INSTANCE_ID and YOUR_SECRET_KEY with the credentials from your Pusher Beams console.

Next we need to compress the directory we have been working in and make a .zip such that we can upload our code and dependencies to our function later on. Download the Make file from the source code repository here and put it in your working directory. Run the command:

   $ make build

This will create a zip file called Python.zip with all the dependencies packaged within it.

Creating a Lambda function

Log in or create an account to access your AWS console here. Once you are logged in use the search bar to find Lambda and select it from the list.

Note: Set your AWS region to N. Virginia in the top right if it is not already.
You should be redirected to the Lambda service and see an option Create Function, select this. Choose the Author from Scratch option at the top of the next page. This will provide us a basic “hello world” template we can use to create our function. Complete the basic setup as shown in the image below.

  • Function name - Name this whatever you want for example “Pusher-Beams-Python”.
  • Runtime - We will be using Python 3.7 so select this from the drop down list.
  • Execution role - Select Create a new role from AWS policy templates. If you already have a role you would rather use you can select Use an existing role.
  • Role name - You can name this anything you like for example “lambda_basic_execution”.
  • Policy templates - You can leave this blank.

Once complete select the Create function button at the bottom of the page. You should be redirected to your Lambda function console once it has been created. We can ignore the Designersection of the console. This area allows us to tie together different AWS services, you may wish to use this with a production function such that it can be accessed from the wider internet. However, we will just be using the test service for the purpose of this tutorial.

Now we need to upload our code. In the Function code section select the Upload a .zip file from the Code entry type dropdown menu. Use the Upload button to search your local machine for the Python.zip we created earlier. Finally change the Handler to be index.lambda_handler, this will allow AWS Lambda to find our function within our folder. If everything looks like the below image click Savein the top right.

Create your iOS application

Now that we have created our Lambda function, we need to have a user that has actually registered for notifications and signed up for the hello interest so we can test out our implementation. We’re going to create a very basic app that doesn’t actually show anything to the user except for the notification on the lock screen.

Project setup

Create a new Single View App using Xcode and name it something like LambdaPush. Once the project is created we need to install the Beams SDK. Open the terminal and go to the working directory of the newly created project and run the following command.

    $ pod init

Open the newly created Podfile and add the following pod:

    pod 'PushNotifications'

In the terminal run:

    $ pod install

Make sure you close your Xcode project and reopen the newly created Xcode Workspace before continuing. Within your project capabilities make sure you have switched on the Push Notificationscapability. Also turn on the Background Modes capability and tick the box for Remote Notifications.

Open your AppDelegate.swift file and replace its contents with the following. Remembering to replace YOUR_INSTANCE_ID with your Pusher Beams instance ID.

    // AppDelegate.swift
    import UIKit
    import PushNotifications

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
        var window: UIWindow?
        let pushNotifications = PushNotifications.shared

        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            self.pushNotifications.start(instanceId: "YOUR_INSTANCE_ID")
            self.pushNotifications.registerForRemoteNotifications()
            try? self.pushNotifications.subscribe(interest: "hello")

            return true
        }

        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            self.pushNotifications.registerDeviceToken(deviceToken)
        }

        func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
            self.pushNotifications.handleNotification(userInfo: userInfo)
        }
    }

You can now run the application on your iOS device and accept to receive notifications. The SDK will then manage registering our interest in hello. Remember to replace YOUR_INSTANCE_ID with your instance ID credential from your Pusher Beams console.

Testing our implementation

Return to your Lambda function console. In the top right select the Test button. We need to configure a test option. Create a new test event like the below image. Notice how our keys in the JSON object are title and message. These are the event keys we were using in our code to provide the title and body for the push notification.

Once you are done press the Create button at the bottom. The dialog box will close and the test HelloTest should be selected in the dropdown menu by the Test button, Press Test. If everything has worked as expected you should receive a push to your device and a similar log output from your Lambda console.

Conclusion

We’ve learnt how to create an AWS Lambda function using NodeJS that can publish a push notification using Pusher Beams to an iOS device. The source code for this tutorial can be found here.

Top Python Development Companies | Hire Python Developers

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When you look for the developer in hurry you may forget to take note of review and ratings of the company's aspects, but we at TopDevelopers have done a clear analysis of these top reviewed Python development companies listed here and have picked the best ones for you.

List of Best Python Web Development Companies & Expert Python Programmers.

Golang vs. Python - Is Golang Better Than Python? - positronX.io

Golang vs. Python - Is Golang Better Than Python? - positronX.io

In this tutorial we are going to make the comparison between Golang or Python, you will have the complete idea at the end of this tutorial which programming language between Python or Goland you should opt for your next software development project. The web development industry has been in the limelight right from the introduction …

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Description
Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is $74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Anyone looking to start with Python GUI development
Basic knowledge
Access to a computer
Download Python (FREE)
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Signup Login & Registration Programs
Quizzes
Assignments
Job Interview Preparation Questions
& Much More