iOS推送消息實現

向iPhone、iPod Touch發送消息都需要認證的,下面是以向iPhone推送消息:

一、開通“Apple Push Notification Service”

1.進入 Provisioning Protal

2.選擇App IDs

3.選擇要開通“Apple Push Notification service”的AppID,點擊“Configure”鏈接

4.點擊“Enable for Apple Push Notification service”複選框

5.點擊“Configure”按鈕,選擇CSR文件上傳

6.點擊“Download”按鈕,下載CER文件,雙擊導入。

7.選擇“Provisioning”,重新生成Provisioning Profile,下載,導入到XCode。

二、生成PHP端推送消息到Apple服務器時需要的證書文件

1.選定推送服務證書(Apple Development Push Services*),導出到桌面,保存爲Certificates.p12。

2.在終端中運行如下命令:

  1. openssl pkcs12 -clcerts -nokeys -out cert.pem -in Certificates.p12  
  2. openssl pkcs12 -nocerts -out key.pem -in Certificates.p12  
  3. openssl rsa -in key.pem -out key.unencrypted.pem  
  4. cat cert.pem key.unencrypted.pem > ck.pem

ck.pem文件則是PHP推送消息時所使用的證書文件。

三、iPhone中獲取DeviceToken代碼

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
[self alertNotice:@"" withMSG:[NSString stringWithFormat:@"Error in registration. Error: %@", err] cancleButtonTitle:@"Ok" otherButtonTitle:@""];
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"devToken=%@",deviceToken);
[self alertNotice:@"" withMSG:[NSString stringWithFormat:@"devToken=%@",deviceToken] cancleButtonTitle:@"Ok" otherButtonTitle:@""];
}



php執行

Received: by 10.100.92.10 with SMTP id p10mr6809083anb.21.1280402522574;

        Thu, 29 Jul 2010 04:22:02 -0700 (PDT)

X-BeenThere: [email protected]

Received: by 10.101.146.2 with SMTP id y2ls2508785ann.6.p; Thu, 29 Jul 2010 

04:22:01 -0700 (PDT)

MIME-Version: 1.0

Received: by 10.101.179.37 with SMTP id g37mr1055492anp.14.1280402521708; Thu, 

29 Jul 2010 04:22:01 -0700 (PDT)

Received: by i19g2000pro.googlegroups.com with HTTP; Thu, 29 Jul 2010 04:22:01 

-0700 (PDT)

Date: Thu, 29 Jul 2010 04:22:01 -0700 (PDT)

X-IP: 202.131.125.154

User-Agent: G2/1.0

X-HTTP-Via: 1.1 station254.webpollux.local (squid/3.1.4)

X-HTTP-UserAgent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.14) 

Gecko/2009082707 Firefox/3.0.14,gzip(gfe)

Message-ID: <8cc98267-b350-4d1a-9a07-9c62aa3fc5be@i19g2000pro.googlegroups.com>

Subject: Not receiving apns feedback response

From: JP <[email protected]>

To: Easy APNs <[email protected]>

Content-Type: text/plain; charset=ISO-8859-1


Hi All,


I am not receiving any feedback after sending the push notification

though all the result messages confirm the connection to the feedback

server. Pl check the following php code that I have used and help, if

you have any clue:


--------apns.php----------


    <?php

    $deviceToken = '64 characters device token id'; // masked for

security reason


    $message = $_GET['message'] or $message = $argv[1] or $message =

'Dummy Notification';

    $badge = (int)$_GET['badge'] or $badge = (int)$argv[2];

    $sound = $_GET['sound'] or $sound = $argv[3];


    $body = array();

    $body['aps'] = array('alert' => $message);

    if ($badge)

    $body['aps']['badge'] = $badge;

    if ($sound)

    $body['aps']['sound'] = $sound;


    $ctx = stream_context_create();

    $t = stream_context_set_option($ctx, 'ssl', 'local_cert',

'New_cert/cert.pem');


$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";

    }


    $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);

    ?>

-------------------------------------


--------feedback.php----------


    <?php


    $ctx = stream_context_create();

    stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');

    stream_context_set_option($ctx, 'ssl', 'verify_peer', false);


    $fp = stream_socket_client('ssl://feedback.sandbox.push.apple.com:

2196', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $ctx);


    if (!$fp) {

    print "Failed to connect feedback server: $err $errstr\n";

    return;

    }

    else {

    print "Connection to feedback server OK\n";

    }


    print "APNS feedback results\n";

    while ($devcon = fread($fp, 38))

    {

    $arr = unpack("H*", $devcon);

    $rawhex = trim(implode("", $arr));

    $feedbackTime = hexdec(substr($rawhex, 0, 8));

    $feedbackDate = date('Y-m-d H:i', $feedbackTime);

    $feedbackLen = hexdec(substr($rawhex, 8, 4));

    $feedbackDeviceToken = substr($rawhex, 12, 64);

    print "TIMESTAMP:" . $feedbackDate . "\n";

    print "DEVICE ID:" . $feedbackDeviceToken. "\n\n";

    }

    fclose($fp);

    ?>

-------------------------------------


The response that I am repeatedly receiving is as follows:


-----------Response------------


///////////////////////-iMac:APNS_NEW_CERTIFICATES ///////////////////

$

php -f apns.php "Dummy Notification" 2


             1Connection OK

sending message :{"aps":{"alert":"Dummy Notification","badge":2}}

Resource id #7Connection to feedback server OK

APNS feedback results

///////////////////////-iMac:APNS_NEW_CERTIFICATES ///////////////////

$


-------------------------------------


Pl check.

Thanks

JP


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章