设置推送通知服务最糟糕的部分是配置。我遇到的主要障碍是您从 Apple 网站下载的 .cer 文件中有一个证书和一个密钥,我用 C# 编写了一个发送通知的系统服务,并且连接一直失败,因为我已经导出了证书而不是关键。
我不记得最初是谁写的,这是我第一次测试通知服务时用 python 编写的一些代码。我喜欢它,因为它非常简单,并且在测试过程中运行良好。
import socket, ssl, json, struct
# device token returned when the iPhone application
# registers to receive alerts
deviceToken = 'XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXXXXXXX'
thePayLoad = {
'aps': {
'alert':'Oh no! Server\'s Down!',
'sound':'k1DiveAlarm.caf',
'badge':42,
},
'test_data': { 'foo': 'bar' },
}
# Certificate issued by apple and converted to .pem format with openSSL
# Per Apple's Push Notification Guide (end of chapter 3), first export the cert in p12 format
# openssl pkcs12 -in cert.p12 -out cert.pem -nodes
# when prompted "Enter Import Password:" hit return
#
theCertfile = 'cert.pem'
#
theHost = ( 'gateway.sandbox.push.apple.com', 2195 )
#
data = json.dumps( thePayLoad )
# Clear out spaces in the device token and convert to hex
deviceToken = deviceToken.replace(' ','')
byteToken = bytes.fromhex( deviceToken ) # Python 3
# byteToken = deviceToken.decode('hex') # Python 2
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 = theCertfile )
ssl_sock.connect( theHost )
# 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()
还有一个名为 apn_on_rails 的 rails gem,如果您正在开发一个 rails 应用程序,它似乎工作得很好,我今天才看到它并且能够从控制台发送通知。
在 iPhone 端,您只需调用以下命令即可注册所有类型的通知:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
要接收设备令牌,您需要实现以下委托方法:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
在测试期间,您可以使用 NSLog 将 deviceToken 踢到控制台,然后将其粘贴到上面的 python 脚本中,在生产中您显然需要设置一些方法来将令牌获取到您的服务器。
此外,在生产环境中,您需要查询 Apple 的反馈服务并从删除您的应用的用户那里删除设备令牌。