关于apns这玩意,以前也写过不少的博客来介绍它了,国内的文章都是基于同一套代码的.
而正因为对apns了解的少,所以写的代码,以及对它的扩展都是不够完善的.
不过google code上终于有一套相对比较完善的代码了.https://code.google.com/p/apns-php/,其实在最近他已经迁移到了github了(October 26, 2012, Project source code has moved to github. )
看了一下代码,确实不错.
如果是原先的代码,其实一直有一个问题:如果某个token失效了,那么在接下来的10s左右,fwrite的推送都会失败.
虽然苹果提供了feedback的返回,但其实你翻看国内的文章,介绍,都没有告诉你怎么查询feedback,所以我到现在也没有好好的对Feedback处理过那些无效的信息.
上面介绍的这套代码就好很多了.可以进行推送,在失败的话,还能够继续推,如果成功的推送是直接可以进入下一条,不会胡乱浪费资源,真心不错...
代码也很简单:
- $push = new ApnsPush(ApnsAbstract::ENVIRONMENT_SANDBOX, '/dev.pem');
- // Set the Root Certificate Autority to verify the Apple remote peer
- //$push->setRootCertificationAuthority('entrust_root_certification_authority.pem');
- // Increase write interval to 100ms (default value is 10ms).
- // This is an example value, the 10ms default value is OK in most cases.
- // To speed up the sending operations, use Zero as parameter but
- // some messages may be lost.
- // $push->setWriteInterval(100 * 1000);
- // Connect to the Apple Push Notification Service
- $push->connect();
- foreach ($result as $data) {
- $token = $appCache->getAppTokenByUserId($data['receive_userid']);
- if(!$token){
- continue ;
- }
- $token = str_replace(" ","",$token);
- // Instantiate a new Message with a single recipient
- $message = new ApnsMessage($token);
- // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
- // over a ApnsMessage object retrieved with the getErrors() message.
- //$message->setCustomIdentifier(sprintf("Message-Badge-%03d", $i));
- // Set badge icon to "3"
- $message->setBadge( intval($data['cnt']));
- // Add the message to the message queue
- $push->add($message);
- }
- // Send all messages in the message queue
- $push->send();
- // Disconnect from the Apple Push Notification Service
- $push->disconnect();
- // Examine the error message container
- $aErrorQueue = $push->getErrors();
- if (!empty($aErrorQueue)) {
- var_dump($aErrorQueue);
- }
这段代码不要纠结,为什么与官方不一样,因为我在用yii框架的时候没有autoload成功它的 代码,花了5分钟将它全部改成基于namespace的了.