DEV Community

Aditya Varma
Aditya Varma

Posted on

Apple push notifications

To send push notifications to any apple device using apns, I had to spend a considerable amount of time looking at all the alternatives available in python. Then i found an open source library pyapns2. I had almost rejected this library when I was exploring because it did not say any where in the documentation that it supports batching or token based authentication.
When I searched the source code, I was astonished to see that it had support for both but was not documented.

So I updated the documentation and raised a pull request.

For any one who has been facing similar issues below is the example code on how to use the library.

from apns2.client import APNsClient
from apns2.payload import Payload

token_hex = 'b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b87'
payload = Payload(alert="Hello World!", sound="default", badge=1)
topic = 'com.example.App'
client = APNsClient('key.pem', use_sandbox=False, use_alternative_port=False)
client.send_notification(token_hex, payload, topic)

# To send multiple notifications in a batch
Notification = collections.namedtuple('Notification', ['token', 'payload'])
notifications = [Notification(payload=payload, token=token_hex)]
client.send_notification_batch(notifications=notifications, topic=topic)

# To use token based authentication
from apsn2.credentials import TokenCredentials

auth_key_path = 'path/to/auth_key'
auth_key_id = 'app_auth_key_id'
team_id = 'app_team_id'
token_credentials = TokensCredentials(auth_key_path=auth_key_path, auth_key_id=auth_key_id, team_id=team_id)
client = APNsClient(credentials=token_credentials, use_sanbox=False)
client.send_notification_batch(notifications=notifications, topic=topic)

To learn about token based authentication you can have a look at this wonderful resource here

Benchmark:

When I used send_notification for sample token size of 2000 it took me around 10 minutes to send all the notifications.
When I used send_notification_batch for same sample token size it took less than 5 seconds to send out all the notifications.

Top comments (1)

Collapse
 
miqueasgutierrez profile image
miqueasgutierrez

Hello, another good option would be integrating INDIGITALL, it allows you to send Notifications with an animated image, Segmented, Geolocated and many more functions, it is great.

Here you can see the installation guide for your ios platform:
docs.indigitall.com/en/indigitalls...