Notification is the big picture of current day to day applications. So
today we are going to look into iPhone push notification. We already
seen how to send email notification using python. The to hot topic we are going to deep is How to send push notification to iPhone's.
Description
Here we are going to use the Apple push notification service. Through python code we have to send the notification to Apple service with device id. Once we send the notification to apple service, they will take care to deliver this notification to appropriate device.Pre-Requesting
We must enable APNS service. To follow this link to enable the APNS service. APNS will generate the certificate after enable the service.Sample code
The below code snapshot will have the sample code for to send push notification to IOS device through the apple sandbox mode in testing purpose,1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #!/usr/bin/env python import ssl import json import socket import struct import binascii class IOSPNotificationSender(object): def __init__(self, host, port, certificate_path): self.host = host self.port = port self.certificate = certificate_path def send_push_notification(self, token, payload): #the certificate file generated from Provisioning Portal #certfile = '../certificate/sample.pem' certfile = self.certificate # APNS server address (use 'gateway.push.apple.com' for production server) #apns_address = ('gateway.sandbox.push.apple.com', 2195) apns_address = (self.host, self.port) data = json.dumps(payload) # Clear out spaces in the device token and convert to hex deviceToken = token.replace(' ', '') byteToken = deviceToken.decode('hex') theFormat = '!BH32sH%ds' % len(data) theNotification = struct.pack(theFormat, 0, 32, byteToken, len(data), data) # Create our connection using the certfile saved locally ssl_sock = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM), certfile=certfile) ssl_sock.connect(apns_address) # Write out our data ssl_sock.write(theNotification) # Close the connection -- apple would prefer that we keep # a connection open and push data as needed. ssl_sock.close() if __name__ == '__main__': token = '****************************************************************' payload = { 'aps': { 'alert':'Bitcoin price going down as -2.03%', 'sound':'default_received.caf', 'badge':1, }, 'Latest_news': { 'Bitcoin': ' The bit coin as of now down -2.03%' }, } ios_notifier = IOSPNotificationSender('gateway.sandbox.push.apple.com', 2195, '../certificate/sample.pem') ios_notifier.send_push_notification(token, payload) |
No comments:
Post a Comment