您的位置:首页 > 移动开发

Apple PUSH Notication Service (APNS) 配置攻略

2011-10-20 12:54 155 查看
iOs 3.0以后就支持APNS( apple push notication Service).下面介绍怎么配置APNS服务。

APNS 分为客户端与服务器端2个部分:

客户端部分:

 1    创建一个App Id 。如果你已经是apple的注册用户(至少是开发者)。首先登录进入Apple developer program portal

 2   创建好App Id 点击 Configure。选择支持APNS,按照步骤选择你的开发证书(csr)。并下载cer文件双击安装( Apple development iOS push notication Services:xxxxxxxxx)

3    此时 。Mac 上的 keychain 里面 Login 已经包含了想要的证书和密钥,按Control 将 证书和密钥export出。保存为cert.p12 和 key.p12 文件(导出过程需要输入密码。请务必保留这个密码)

4    打开终端。 cd 到保护cert.p12 key.p12的文件夹。将cert.p12 he key.p12转化为pem文件,并进行合并

 openssl pkcs12 -clcerts -nodes -out cert.pem -in cert.p12

openssl pkcs12 -nodes -out key.pem -in key.p12

cat cert.pem key.pem > yourapp.pem

5  生产对应App Id 的 privosion file。并加入XCode。用这个证书对你的应用进行签名(注意,App ID 必须匹配)

6   APNS 客户端主要涉及下面几个API

 6.1 将app注册notification里面.

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {        
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];  
            // other codes here.    
        return YES;
    }

6.2 从APNS上获取测试机的deviceToken.

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        NSLog(@"deviceToken: %@", deviceToken);
    }
     
    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
        NSLog(@"Error in registration. Error: %@", error);
    }

3  当收到 PUSH 的时候,处理

    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    {
        
        NSLog(@" 收到推送消息 : %@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
        if ([[userInfo objectForKey:@"aps"] objectForKey:@"alert"]!=NULL) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"推送通知"
                                                            message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]
                                                           delegate:self
                                                  cancelButtonTitle:@" 关闭"
                                                  otherButtonTitles:@" 更新状态",nil];
            [alert show];
            [alert release];
        }

客户端部分基本上完成了,需要保留好 pem文件,p12文件的密码,和获得的DeviceToke,服务器方面需要使用到

服务器方面:

1)php驱动。需要将ck.pem和php脚本放到server 上。全部的php代码是:
    

    <?php
    $deviceToken = '6974ac11 870e09fa 00e2238e 8cfafc7d 2052e342 182f5b57 fabca445 42b72e1b'; // 可以用你获得的DeviceToken替换
    $pass = '123456';   // Passphrase for the private key (ck.pem file)  
     
    // Get the parameters from http get or from command line
    $message = $_GET['message'] or $message = $argv[1] or $message = 'A test message from worldcup';
    $badge = (int)$_GET['badge'] or $badge = (int)$argv[2];
    $sound = $_GET['sound'] or $sound = $argv[3];
     
    // Construct the notification payload
    $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
    $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
    if (!$fp) {
        print "Failed to connect $err $errstr\n";
        return;
    }
    else {
       print "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 "Sending message :" . $payload . "\n";  
    fwrite($fp, $msg);
    fclose($fp);
    ?>

请 求一次 http://127.0.0.1/apns/apns.php?message=A%20test%20message%20from%20localhost&badge=2&sound=received5.caf就 会向APNS进行一次推送。我的请求结果如下:

    Connection OK
    Sending message :{"aps":{"alert":"A test message from localhost","badge":2,"sound":"received5.caf"}}

将php部署好,在IE中访问即可。

经过测试,可以在真机上获得Push消息。

在iPhone4.3已测试通过。


原文地址: http://blog.csdn.net/vaminal/article/details/6616227
昨天虽然配置APNS成功,但对它的原理并并不是很清楚。今天翻了一下Erica Sadun的cookbook,发现专门有一章是讲这个的,对它的来龙去脉讲得比较清楚。笔记一下。

“通过APNS推送通知需要3个条件:SSL证书,设备ID和要发送的通知得自定义有效内容。”
SSL证书可在iOSProvisioning
Portal 的App IDs菜单中一步步按向导生成
”一个令牌与一个设备关联。设备令牌是作为注册的副产品而创建的。接受到注册请求后,ios即刻联络APNS并等待其返回一个设备令牌。APNS构建设备令牌并将其返回到ios。应用程序通过委托回调-(void)application:(UIApplication*)appdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
获得设备令牌“。

“只有应用程序得到一个设备令牌并将其发送到服务器后才能接收推送消息。应用程序必须将设备令牌发送到推送实际通知得外设备”。
“通知的有效内容必须包括一个aps字典,定义要发送给用户的声音,标志和警告得属性。自定义数据字典限定在256B以内。通知内容可转化为JSON格式”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: