IOS推送消息是许多IOS应用都具备的功能,最近也在研究这个功能,参考了很多资料终于搞定了,下面就把步骤拿出来分享下(网上同样的步骤可以查到很多,本文转自http://zxs19861202.iteye.com/blog/1532460
iOS消息推送的工作机制可以简单的用下图来概括:
Provider是指某个iPhone软件的Push服务器,APNS是Apple Push NotificationService的缩写,是苹果的服务器。
上图可以分为三个阶段:
第一阶段:应用程序把要发送的消息、目的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应用程序。
无论是iPhone客户端和APNS,还是Provider和APNS,都需要通过证书进行连接。
下面我介绍一下几种用到的证书。
一、CSR文件
1、生成Certificate Signing Request(CSR)
2、填写你的邮箱和常用名称,并选择保存到硬盘。
点击继续:
这样就在本地生成了一个Push.certSigningRequest文件。
二、p12文件
1、导出密钥。
2、输入你的密码。
这样就生成了一个Push.p12文件。
三、SSL certificate文件
1、用你付过费的帐号登录到iOS Provisioning Portal,并新建一个App ID,这个过程可以参考:iOS应用的真机调试,这样就会生成下面这条记录:
2、点击右侧的Configure:
3、点击Development Push SSL Certificate一行后的Configure:
4、点击Continue:
5、选择前面生成好的Push.certSigningRequest文件,点击Generate,出现如下所示的页面:
6、点击Continue:
7、点击Download,并将文件命名为aps_developer_identity.cer。
8、点击Done,你会发现状态变成了Enabled:
到现在为止,我们已经生成了三个文件:
1、Push.certSigningRequest
2、Push.p12
3、aps_developer_identity.cer
双击aps_developer_dientity.cer 注册到你的钥匙串中,这样你的钥匙串中就会有
二、准备profile证书,因为推送消息只能再真机上测试,所以要建一个profile证书
点击"new profile"为上面新建的APP ID建个profile,成功之后下载*_Dev_Profile.mobileprovision
双击将其加入到xcode 的Provisioning Profiles 中,这里有一点要注意,再将这个加入xcode之前如果之前已经加入过一定要把之前加入的删掉,如果有多个的话会出错。
三、工程代码
到这里证书已经准备完毕,接下来,我们在xcode中新建一个测试工程,注意设置工程的Bundle Identifier必须与上面建的APP ID里的相同
在didFinishLaunchingWithOptions 中加入一下代码
-(BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self.window makeKeyAndVisible];
[[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
return YES;
}
-(void)application:(UIApplication *)applicationdidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken{
NSLog(@"regisgersuccess:%@", pToken);
//注册成功,将deviceToken保存到应用服务器数据库中
}
-(void)application:(UIApplication *)applicationdidReceiveRemoteNotification:(NSDictionary *)userInfo{
// 处理推送消息
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"通知" message:@"我的信息" delegate:selfcancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
[alert show];
[alert release];
NSLog(@"%@",userInfo);
}
-(void)application:(UIApplication *)applicationdidFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
NSLog(@"Registfail%@",error);
}
到这里一切顺利的话我们就可以在真机运行了,注册成功我们会得到iphone的deviceToken,
Mytoken is:
<740f4707bebcf74f 9b7c25d4 8e335894 5f6aa01d a5ddb387 462c7eaf61bb78ad>
四、服务端证书
(1)在应用服务器采用php的方式将消息推送给APNS,
pem文件是服务器向苹果服务器做推送时候需要的文件,主要是做服务器的小伙伴们要用, 下面介绍一下pem文件的生成。
- 打开Keychain Access,在Certificates里面找到上篇文章中介绍的包含推送的证书。分别将certificate和private key导出得到.p12文件。例如:Apple Development Push Services > Export “Apple Development Push Services ID123”,保存为 apns-dev-cert.p12。对“Private Key”做同样操作,保存为 apns-dev-key.p12 文件。
- 需要通过终端命令将这些文件转换为PEM格式:
openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12
openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12
此处要求输入一个密码,输入123456.
- 移除密码(上面的123456)
openssl rsa -in apns-dev-key.pem -out apns-dev-key.pem
- 最后,你需要将键和许可文件合成为apns-dev.pem文件,此文件在连接到APNS时需要使用:
cat apns-dev-cert.pem apns-dev-key.pem > apns-dev.pem
openssl pkcs12 -nocerts -out apns-dis-key.pem -in apns-dis-key.p12
为了测试证书是否工作,执行下面的命令:
$telnet gateway.sandbox.push.apple.com 2195
Trying17.172.232.226…
Connected togateway.sandbox.push-apple.com.akadns.net.
Escapecharacter is ‘^]’.
它将尝试发送一个规则的,不加密的连接到APNS服务。如果你看到上面的反馈,那说明你的MAC能够到达APNS。按下Ctrl+C关闭连接。如果得到一个错误信息,那么你需要确保你的防火墙允许2195端口。
然后再次连接,这次用我们的SSL证书和私钥来设置一个安全的连接:
$openssl s_client -connectgateway.sandbox.push.apple.com:2195
-certPushChatCert.pem -key PushChatKey.pem
Enterpass phrase for PushChatKey.pem:
你会看到一个完整的输出,让你明白OpenSSL在后台做什么。如果连接是成功的,你可以键入一些字符。当你按下回车后,服务就会断开连接。如果在建立连接时有问题,OpenSSL将会给你一个错误消息,
ck.pem文件就是我们需要得到php连接APNS的文件,将ck.pem和push.php放入同一目录上传到服务器,push.php的代码如下:
<?php
//这里是我们上面得到的deviceToken,直接复制过来(记得去掉空格)
$deviceToken= '740f4707bebcf74f 9b7c25d48e3358945f6aa01da5ddb387462c7eaf 61bb78ad';
// Put your private key'spassphrase here:
$passphrase= 'abc123456';
// Put your alert messagehere:
$message= 'My first push test!';
////////////////////////////////////////////////////////////////////////////////
$ctx =stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase',$passphrase);
// Open a connection to the APNSserver
//这个为正是的发布地址
//$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 payloadbody
$body['aps'] = array(
'alert' =>$message,
'sound' => 'default'
);
// Encode the payload asJSON
$payload =json_encode($body);
// Build the binarynotification
$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 successfullydelivered' . PHP_EOL;
// Close the connection to theserver
fclose($fp);
?>
接下来我们访问http://localhost/push/push.php
iphone就会接收到一条推送消息了,如果有问题的话就检查上面的操作步骤,特别是加红的部分
另外去除标记的方法为,在viewDidApper中加入
int badge =[UIApplication sharedApplication].applicationIconBadgeNumber;
if(badge > 0)
{
badge--;
[UIApplication sharedApplication].applicationIconBadgeNumber = badge;
}
搜(2)JAVA服务跟PHP相同
(3).NET服务如下

2、生成*.p12文件
导出密钥,并输入你的密码。
到现在为止,我们已经生成了3个文件。
1、certsign.certSigningRequest
2、key.p12
3、cert.cer
从客户端得的deviceToken。
发送通知的.net应用程序出来需要知道deviceToken之外,还需要一个与APNS连接的证书。
这个证书可以通过我们前面生成的两个文件中得到。
使用OpenSSL生成.net和APNS通信的证书文件。
1、将cert.cer转换成 cert.pem格式。
openssl x509 -in cert.cer -inform DER -out cert.pem -outform PEM
2、将p12格式的私钥转换成pem,需要设置4次密码,这里密码都设置为:abc123。
openssl pkcs12 -nocerts -out key.pem -in key.p12
3、用certificate和the key
openssl pkcs12 -export -in cert.pem -inkey key.pem -certfile certsign.certSigningRequest -name "cert" -out apns.p12
这样我们就得到了在.net应用程序中使用的证书文件:apns.p12。
net的生成证书就是这个样子。其他程序的方式会不一样。切记切记
有个开源的类库:apns-sharp。
地址是:http://code.google.com/p/apns-sharp/。
我们下载源代码,对里面的JdSoft.Apple.Apns.Notifications做相应的调整就能用了。
正式环境的话