1.平常開發通常使用第三方推送, 這裏自己整理記錄不使用第三方推送的操作流程。
2.登陸 https://developer.apple.com, 在Identifiers App IDs 下, 找到需要推送的app, 找到推送選項, 勾選, 上傳文件, 生成證書,下載並導入鑰匙鏈。
3.在鑰匙鏈中找到我們下載的證書,
4.接下里競選中Apple xxxx Services 導出, 格式爲.p12文件給自己服務器。 至此, 證書已經導出完成。
5.xcode 設置:
framework導入, 需要注意UserNotifications, 如果在編譯報錯, 適配iOS8以下版本, 這裏要選optional.
6.代碼,請求推送權限
UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
獲取token, 上傳服務器,
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
//獲取token , 上傳服務器
}
7,客戶端單獨測試。這裏使用php 代碼進行測試, 因爲mac 自帶。
導出證書,並且命名爲aps_dev.cer
同樣操作, 導出.p12文件。設置密碼123456
接下來, 打開控制檯, cd 到存儲目錄 .
執行以下操作:
a. openssl x509 -in aps_dev.cer -inform der -out PushChatCert.pem
b. openssl pkcs12 -nocerts -out PushChatKey.pem -in push.p12
c. cat PushChatCert.pem PushChatKey.pem > ck.pem
至此, 文件已經制作完畢,打開文本編輯器。 輸入php 代碼, 並執行, 即可
<?php
// Put your device token here (without spaces):
$deviceToken = '450f094a8c9032189ab06d3e26725d247150d5fa71520c6ee5cf1641d54ccc34 ';
// Put your private key's passphrase here:密語
$passphrase = '123456';
// Put your alert message here:
$message = '820fc655ec5d2ead8d37889689e0c8f078a6d236a40e25d9d80072f88125ec1c';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
// 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);
// $fp = stream_socket_client(
// 'ssl://gateway.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',
'badge' => 0
);
// 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 要放在同一個目錄下面。
網上有些推送信息太老, 有點不適用了。在此記錄方便後面使用。