1

我正在构建一个应用程序,我在其中使用 NSUserDefaults 来存储各种信息,包括用于 iOS 上的 APNS 的 deviceToken。它当前的工作方式是用户提交请求,并将条目添加到 XML,该 XML 中的元素之一称为 deviceToken。当有人响应该请求时,它会触发页面底部的 PHP 向该特定请求的 deviceToken 发送推送通知。我的问题是有些人拥有不止一台设备,最好将推送通知发送到该所有者的所有设备。正如您在下面的代码中看到的,我有 2 个用于 deviceTokens 的区域。如果 XML 包含 2 个设备令牌,那么一切都很好。问题是,对于只有 1 个令牌的那些,即使是一个也将无法交付。

<?php
$first_name = $_POST['first_name'];
 $last_name = $_POST['last_name'];
 $title = $_POST['title'];
 $deviceToken = $_POST['deviceToken'];
 $deviceToken2 = $_POST['deviceToken2'];
$xml = simplexml_load_file("http://www.URL.xml") or die("Not loaded!\n");

$passphrase = 'passphrase';

// Put your alert message here:
$message = 'Someone just responded to you!';

////////////////////////////////////////////////////////////////////////////////

$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.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;
$msg2 = chr(0) . pack('n', 32) . pack('H*', $deviceToken2) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
$result = fwrite($fp, $msg2, strlen($msg2));


if (!$result)
    echo 'Message not delivered' . PHP_EOL;
else
    echo 'Message successfully delivered' . PHP_EOL;

// Close the connection to the server
fclose($fp);  
?>
4

1 回答 1

1

您可以做的是将该函数用作通用函数:也就是说,它接受一个设备令牌对象。这可以是单个字符串,也可以是多个字符串的数组。

然后,使用该函数检查是否$deviceToken是数组。is_array参考:http ://us3.php.net/manual/en/function.is-array.php

为此,您可能需要重写一小部分代码。所以总的来说,它看起来像这样:

if(is_array($deviceToken)) {
    // Iterate over the array and call the same function with each string
    return;
}

// You're code to actually send the push notification just as you have it above.
于 2014-06-26T06:45:50.137 回答