ios 实现推送消息

 

iOS消息推送的工做机制能够简单的用下图来归纳:php


 

Provider是指某个iPhone软件的Push服务器,APNS是Apple Push Notification Service的缩写,是苹果的服务器。node

 

上图能够分为三个阶段:ios

第一阶段:应用程序把要发送的消息、目的iPhone的标识打包,发给APNS。 数据库

第二阶段:APNS在自身的已注册Push服务的iPhone列表中,查找有相应标识的iPhone,并把消息发送到iPhone。 编程

第三阶段:iPhone把发来的消息传递给相应的应用程序,而且按照设定弹出Push通知。json

 

从上图咱们能够看到:服务器

一、应用程序注册消息推送。app

二、iOS从APNS Server获取device token,应用程序接收device token。iphone

三、应用程序将device token发送给PUSH服务端程序。socket

四、服务端程序向APNS服务发送消息。

五、APNS服务将消息发送给iPhone应用程序。

步骤1、

建立须要的证书 & 使用PHP编写服务器端推送代码

1. 登陆 iPhone Developer Connection Portal(http://developer.apple.com/iphone/manage/overview/index.action ) 而后点击 App IDs
2. 建立一个 Apple ID ,如: com.tadpole.TestAPNs  注意:通配符 ID 不能用于推送通知服务。
3. 点击Apple ID旁的“Configure”,根据“向导” 的步骤生成一个签名上传,而后下载生成的许可证。
4. 双击.cer文件将你的 aps_development.cer 导入Keychain中。
5. 在Mac上打开“钥匙串访问”,而后在“登陆”中选择 "密钥"分类,找到咱们建立的证书,而后右击“Apple Development IOS Push Services: com.tadpole.TestAPNs” > 导出 “Apple Development IOS Push Services: com.tadpole.TestAPNs”。保存为 cert.p12 文件。
6. 经过终端命令将这个cert.p12文件转换为PEM格式,打开终端,cd  进入证书所在目录,执行以下命令:

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

执行完上面命令会在当前目录下生成一个名为apple_push_notification_production.pem文件,这个文件就是咱们须要获得php链接APNS 的文件,将apple_push_notification_production.pem和push.php放入同一目录上传到服务器,push.php的代码以下:

 

<?php 

// 这里是咱们上面获得的deviceToken,直接复制过来(记得去掉空格

$deviceToken = '740f4707bebcf74f 9b7c25d4 8e3358945f6aa01da5ddb387462c7eaf 61bb78ad';

 

// Put your private key's passphrase here:

$passphrase = 'abc123456';

 

// Put your alert message here:

$message = 'My first push test!';

 

////////////////////////////////////////////////////////////////////////////////

 

$ctx = stream_context_create();

stream_context_set_option($ctx, 'ssl''local_cert''apple_push_notification_production.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, $ctx);

//这个是沙盒测试地址,发布到appstore后记得修改哦

$fp = stream_socket_client(

'ssl://gateway.sandbox.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 APNS' . PHP_EOL;

 

// Create the payload body

$body['aps'] = array(

'alert' => $message,

'sound' => 'default'

);

 

// Encode the payload as JSON

$payload = json_encode($body);

 

// Build the binary notification

$msg = chr(0. pack('n'32. pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;

 

// Send it to the server

$result = fwrite($fp, $msg, strlen($msg));

 

if (!$result)

echo 'Message not delivered' . PHP_EOL;

else

echo 'Message successfully delivered' . PHP_EOL;

 

// Close the connection to the server

fclose($fp);

?>

 

步骤二

建立一个具有推送通知的应用

首先,咱们须要先对Xcode项目进行一些设置,确保App ID和provisioning profile都被设置成良好的状态。作开发吗,

1.在Supporting Files文件夹下选中ProjectName-Info.plist,对右侧视图中的Bundle Identifier选项进行修改,和你本身建立的App ID保持一致(形如:com.parseSampleApp)。

2.在左侧的菜单中选中刚建立的project文件,在下面找到Build Settings而后搜索Code Signing Identity。

3.将对应provisioning profile的全部的值所有设置好。

4.选择左手边Targets下面的项目名称,再次找到Build Settings,来到Code Signing Identity区域,确保全部的值都和新的provisioning profile保持一致。

代码环节

接下来就开始进入编程模式了。咱们须要对应用程序代理(app delegate)进行少许的修改,从而使得咱们的应用能够接受到推送通知。步骤以下:

1.注册设备须要在app delegate的[application:didFinishLaunchingWithOptions:]方法中调用[application registerForRemoteNotificationTypes:]方法,代码以下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{    

    // Register for push notifications

    [application registerForRemoteNotificationTypes:

     UIRemoteNotificationTypeBadge |

     UIRemoteNotificationTypeAlert |

     UIRemoteNotificationTypeSound];

    returnYES;

}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken {

     NSLog(@"regisger success:%@", pToken);   

    //注册成功,deviceToken保存到应用服务器数据库中,由于在写向ios推送信息的服务器端程序时要用到这个

}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

    // 处理推送消息

    NSLog(@"userInfo == %@",userInfo);    

    NSString *message = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];

    UIAlertView *createUserResponseAlert = [[UIAlertViewalloc] initWithTitle:@"提示

                                  message: message

                                  delegate:self 

                               cancelButtonTitle:@"取消

                               otherButtonTitles: @"确认",

                                          nil];

    [createUserResponseAlert show];

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

    NSLog(@"Regist fail%@",error); 

到这里一切顺利的话咱们就能够在真机运行了,注册成功咱们会获得iphone 的deviceToken,

 

步骤3、

接下来咱们访问http://localhost/push/push.php

iphone就会接收到一条推送消息了,若是有问题的话就检查上面的操做步骤,特别是加红的部分

另外去除标记的方法为,在viewDidApper中加入

int badge = [UIApplication sharedApplication].applicationIconBadgeNumber;

    if(badge > 0)

    {

        badge--;

        [UIApplication sharedApplication].applicationIconBadgeNumber = badge;

    }

相关文章
相关标签/搜索