我正在按照本教程为我的应用程序提供APN服务
这是AppDelegate.swift中的方法
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil )
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let token = deviceToken.description.stringByReplacingOccurrencesOfString(" ", withString: "")
print("Got token data! \(token)")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Couldn't register: \(error)")
}
我运行应用后,系统会提示我从此应用启用推送通知,然后启用它。
我已在控制台中打印设备令牌
然后我用这个PHP代码发送通知:
<?php
// Put your device token here (without spaces):
$deviceToken = 'c1d7b8960fb94d633e9fbf2e7d2aa0748be4b3e32dc3869a0125ca607813e8a1';
// Put your private key's passphrase here:
$passphrase = "xxxxxxxxxx";
// Put your alert message here:
$message = 'My first push notification!';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
在终端我跑了php phpfilename.php
然后我得到了
连接到APNS
消息已成功发送
但我没有得到通知,
此外,我使用了 this app 并显示了此错误:
Notification error: APN invalid token