我创建iOS应用程序,并为我们的推送通知,我们正在使用亚马逊的简单通知服务(SNS)。
I'm creating an iOS app, and for our push notifications, we're using Amazon's Simple Notification Service (SNS).
SNS是美好的,但文档是pretty的稀疏。我使用博托,亚马逊的Python库,我已经找到了如何发送纯-Text推送通知:
SNS is wonderful, but the documentation is pretty sparse. I'm using boto, Amazon's Python library, and I've figured out how to send plain-text push notifications:
device_arn = 'MY ENDPOINT ARN GOES HERE'
plain_text_message = 'a plaintext message'
sns.publish(message=plain_text_message,target_arn=device_arn)
不过,目前还不清楚从文档是如何创建一个苹果推送通知服务(APNS)消息。我需要发送声音并随着推送通知徽章,但无法弄清楚如何格式化JSON的消息。
However, what's not clear from the documentation is how to create an an Apple Push Notification Service (APNS) message. I need to send a sound and a badge along with the push notification, but can't figure out how to format the JSON for the message.
下面是我最好的猜测至今:
Here's my best guess so far:
message = {'default':'default message', 'message':{'APNS_SANDBOX':{'aps':{'alert':'inner message','sound':'mySound.caf'}}}}
messageJSON = json.dumps(message,ensure_ascii=False)
sns.publish(message=messageJSON,target_arn=device_arn,message_structure='json')
当我运行此code,但是,所有我的通知看到的是默认消息 - 这意味着,亚马逊SNS拒绝了我的消息的格式,并显示在默认
代替。
When I run this code, though, all I see on the notification is "default message" - which means that Amazon SNS rejected my message's format, and displayed the default
instead.
如何正确格式化这个JSON?
我想它了! 事实证明,APNS有效载荷为EN codeD,因为较大的有效载荷中的字符串 - 它完全适用
I figured it out! Turns out, the APNS payload has to be encoded as a string within the larger payload - and it totally works.
下面是最终的,工作code:
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')
下面是一个什么样的这个code打算在演练:
首先,创建蟒蛇字典APNS:
First, create the python dictionary for APNS:
apns_dict = {'aps':{'alert':'inner message','sound':'mySound.caf'}}
二,采取的字典,并把它变成一个JSON格式的字符串:
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}
接下来,我们EN code的是的在自己的JSON格式的字符串:
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')