Apple Push Notifications With Foreign Accent Characters Not Receiving

孤者浪人 提交于 2019-12-13 14:02:33

问题


I'm sending push notifications and when the message contains foreign characters (Turkish in my case) like İ, ş, ç, ğ... The message does not arrive to devices.

Here's my code:

$message = 'THİS is push';
$passphrase = 'mypass';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'MyPemFile.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 Apple service. ' . PHP_EOL;

// Encode the payload as JSON
$body['aps'] = array(
    'alert' => $message,
    'sound' => 'default'
    );
$payload = json_encode($body);

$result = 'Start'.PHP_EOL;
$tokenArray = array('mytoken');
foreach ($tokenArray as $item)
{
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
    echo 'Failed message'.PHP_EOL;
else
    echo 'Successful message'.PHP_EOL;
}

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

I have tried encoding $message variable with utf8_encode() but the message received as "THÝS is push". And other ways like iconv() didn't work for me, some of them cropped Turkish characters, some didn't receive at all.

I also have

header('content-type: text/html; charset: utf-8');

and

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

in my page. I don't think the problem appears while I set the value but maybe with pack() function.

Any ideas to solve this without replacing characters with English?


回答1:


All I had to do was replacing the Turkish characters with following script:

function tr_to_utf($text) {   
    $text = trim($text);    
    $search = array('Ü','Ş','Ğ','Ç','İ','Ö','ü','ş','ğ','ç','ı','ö');  
    $replace = array('Ü','Å','&#286;','Ç','İ','Ö','ü','ÅŸ','ÄŸ','ç','ı','ö');
    $new_text = str_replace($search,$replace,$text);    
    return $new_text;  
}

Now it is working with no problems.

This is the source.




回答2:


The "n" parameter means, that you pack as unsigned short (always 16 bit, big endian byte order). I`m not sure how Apple CPU hardware handle the instructions and how convert them, but is different from the PC for sure. Try to switch the byte order, use "v" unsigned short (always 16 bit, little endian byte order).



来源:https://stackoverflow.com/questions/12704638/apple-push-notifications-with-foreign-accent-characters-not-receiving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!