Format APNS-style JSON message in Python for use with Amazon SNS

北城以北 提交于 2019-12-02 20:37:27

I figured it out! Turns out, the APNS payload has to be encoded as a string within the larger payload - and it totally works.

Here's the final, working code:

apns_dict = {'aps':{'alert':'inner message','sound':'mySound.caf'}}
apns_string = json.dumps(apns_dict,ensure_ascii=False)
message = {'default':'default message','APNS_SANDBOX':apns_string}
messageJSON = json.dumps(message,ensure_ascii=False)
sns.publish(message=messageJSON,target_arn=device_arn,message_structure='json')

Here's a walkthrough of what's going on in this code:

First, create the python dictionary for APNS:

apns_dict = {'aps':{'alert':'inner message','sound':'mySound.caf'}}

Second, take that dictionary, and turn it into a JSON-formatted string:

apns_string = json.dumps(apns_dict,ensure_ascii=False)

Third, put that string into the larger payload:

message = {'default':'default message','APNS_SANDBOX':apns_string}

Next, we encode that in its own JSON-formatted string:

messageJSON = json.dumps(message,ensure_ascii=False)

The resulting string can then be published using boto:

sns.publish(message=messageJSON,target_arn=device_arn,message_structure='json')

When I use the SNS publish tool it autogenerates JSON that looks like this:

{ 
    "default": "<enter your message here>", 
    "email": "<enter your message here>", 
    "sqs": "<enter your message here>", 
    "http": "<enter your message here>", 
    "https": "<enter your message here>", 
    "sms": "<enter your message here>", 
    "APNS": "{\"aps\":{\"alert\": \"<message>\",\"sound\":\"default\"} }", 
    "GCM": "{ \"data\": { \"message\": \"<message>\" } }", 
    "ADM": "{ \"data\": { \"message\": \"<message>\" } }" 
 }

This looks closer to the spec talked about by apple in their "Notification Payload" section. Where they state that the message should be

a JSON dictionary object (as defined by RFC 4627). 
This dictionary must contain another dictionary identified by the key aps.
The aps dictionary contains one or more properties

Have you tried providing a message closer to that specification? Something like this for instance:

{
    'default':'default message', 
    {
        'aps':{
            'alert':'inner message',
            'sound':'mySound.caf'
         }
    }
 }

Or following the example from the publish SNS publish tool:

{
    'default':'default message',
    'APNS': {
        'aps':{
            'alert':'inner message',
            'sound':'mySound.caf'
         }\
     }
 }

Maybe also using their backslash escaping.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!