iOS 中的重要功能--推送

来源:互联网 发布:淘宝上怎么卖东西 编辑:程序博客网 时间:2024/05/16 09:31

1、首先进入开发者中心中创建应用的APP ID(bundle ID).



2. 创建完毕后点击app id ,然后点击edit,到Push Notifications中创建证书


3.证书创建完毕,双击安装,可以在钥匙串中看到:


4.分别右键导出证书和密钥,命名为cert.p12和key.p12,保存到桌面的一个文件夹下

5.打开终端,cd命令更改路径到这个文件夹。再终端输入一下四个命令:

openssl pkcs12 -clcerts -nokeys -out cert.pem -in cert.p12
openssl pkcs12 -nocerts -out key.pem -in key.p12  
openssl rsa -in key.pem -out key.unencrypted.pem(如果需要对key不进行加密)  
cat cert.pem key.unencrypted.pem > ck.pem(合并两个pem生成ck.pem)

6.将生成的四个pem文件和下面的index.php文件放到服务器上去。(服务器的搭建特别简单,下载最新版的xampp,它集成了apache,mysql,php,安装就可以搭建一个本地的服务器了)。服务器端配置完成。

7.继续在开发者中心生成调试需要用得几个Provisioning Profile(授权文件),程序中添加推送代码:

 if (IOS8ORLATER) {

        [[UIApplicationsharedApplication]registerForRemoteNotifications];

        [[UIApplicationsharedApplication]registerUserNotificationSettings:[UIUserNotificationSettingssettingsForTypes:(UIRemoteNotificationTypeAlert |UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound|UIRemoteNotificationTypeNewsstandContentAvailability)categories:nil]];

    }

   else {

        [[UIApplicationsharedApplication]registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert |UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];

    }


8.调试程序取得设备token,将token粘贴到index.php中的“你的设备token”中,然后在浏览器中运行index.php文件,你就能听到叮的一声,说明推送成功啦。(记住要关掉程序才行,打开程序的时候能收到推动但是其实是没有反应的,需要在程序中处理,比如写个弹出框之类的)


附录:index.php代码

<?php    $deviceToken = '你的设备token';     // Get the parameters from http get or from command line    $message = $_GET['message'] or $message = $argv[1] or $message = '推送消息';    $badge = (int)$_GET['badge'] or $badge = (int)$argv[2] or $badge = 1;    $sound = $_GET['sound'] or $sound = $argv[3] or $sound = 'default';    $body = array();    $body['aps'] = array('alert' => $message);    if ($badge)    $body['aps']['badge'] = $badge;    if ($sound)    $body['aps']['sound'] = $sound;    /* End of Configurable Items */    $ctx = stream_context_create();    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');    // assume the private key passphase was removed.    //stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);    // connect to apns 测试专用sandbox    $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);    // connect to apns 产品 用的时候解开注释,将测试的部分注释。    //$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);    if (!$fp) {        print "Failed to connect $err $errstr\n";        return;    }    else {        print "Successfully Connection OK\n<br/>";    }    // send message    $payload = json_encode($body);    $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;    print "return message :" . $payload . "\n";    fwrite($fp, $msg);    fclose($fp);    ?>





0 0