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

iOS消息推送的工作机制

2016-04-09 15:21 417 查看
iOS消息推送的工作机制可以简单的用下图来概括:



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

上图可以分为三个阶段:

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

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

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



从上图我们可以看到:

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

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

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

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

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

步骤一、

创建需要的证书 & 使用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,

步骤三、

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

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

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

int badge = [UIApplication sharedApplication].applicationIconBadgeNumber;

if(badge > 0)

{

badge--;

[UIApplication sharedApplication].applicationIconBadgeNumber =
badge;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: