应用增加推送功能

来源:互联网 发布:网络水晶头哪个牌子好 编辑:程序博客网 时间:2024/06/01 09:07

ios的推送原理:注意(如果只是在app中实现推送功能那么必须先要测试然后才能发布这里只是在没有上线的情况下给app增加推送功能所以我们用的这写证书都是开发证书,如果需要发布那么还需要创建发布证书流程基本一样)


1.provide:是给手机发送消息的服务器《如果用的是第三方服务的话那么这给就是第三方服务器》

2.apns:是苹果涌来管理所有应用的消息的推送服务器。

3.iphone:则是手机、

4ClientApp:你的应用;


推送原理:就是如果你要给你的应用发送一条推送信息那么你只要把你的信息和device token发送给apns 然后apns根据deviece token 查询到某一个已经开通可以接受某一应用的推送功能的手机,然后把消息推送给这给手机。《前提是当一个手机第一次下载我们的应用的时候告诉他是否开通消息推送功能如果开通了那么上面的操作可以继续反之不能。还有最最前提的是你的应用要开通推送功能下面第二部分


二给应用添加消息推送功能;

推送分为:本地和远程,远程推送分为5个流程

1,给应用创建身份证,创建身份证需要准备一些文件吧,所以我们要在mac电脑上做一些准备工作,第一步:打开钥匙串访问--》选择证书管理--》选择从证书颁发机构请求证书--》证书信息里面就填你的开发者账号吧,好记然后选择保存到磁盘,这时候我们有了一个CertificateSigningRequest.certSigningRequest的证书

这给证书后面会用到,打个比方吧这给证书就是你要给应用创建身份证所要提交给苹果官方的一个电脑代号《就是身份证的归属地》我们称这给证书为csr证书


第一步我们已经完成,要去提交材料了那么我们必须去苹果官网,所以我们去苹果开发者网址:https://developer.apple.com/选择右上角的member Center(会员中心)登入你的帐号然后选择证书选项


会跳转到

(选择证书)certificates是证书(通行证证书里面有开发者证书(development certificates)和发布者证书(distribution certificates)开发者证书主要是授权mac设备的开发权限,2⃣️发布证书主要是设置mac发布权限  


 而identifiers是标识符:appldis pass type ids  website push ids,其中app ID是应用的唯一标示符 每一个应用的app ID是不一样的


Devices:用于创建测试设备的 用于真机调试,iOS 7.0以后不需要创建证书也可以真机调试了

Pasted Graphic 3.tiff

上面介绍的几个最终跳转的都是同一个界面

20141117101737015.png

Development选项的作用顾名思义就是用来作为开发使用的证书,Production选项则是用来发布产品使用的,名称很陌生是不是,之

前的开发者网页是没有这一选项的,可能是苹果把他修改了,用这个名称更加能让人理解吧(字面上解释就是产品么)。两个选项生

成证书的步骤是一样的,现在我们使用开发者的选项进行证书的制作,步骤如下:选择Development选项


点击上面的创建证书:(注意选择apple push Notification service ssl 那个证书)



Pasted Graphic 5.tiff

选择apns选项点击Gentrate进入到

Pasted Graphic 8.tiff


这给app ID下面会讲怎么创建,这边是创建好的了app ID

点击continue进入到


Pasted Graphic 7.tiff

&&&&这边酒需要用到我们刚采第一步创建的csr证书了,选择choose file 把证书圩镇到这给证书以后点击gentrate



Pasted Graphic 9.tiff

选择download 下载证书我们得到了一个ps_development。cer的证书





接下来我们创建一个app ID就是上面需要用到的那个app ID


点击identifiers 选项下面的app ID 点击+

Pasted Graphic 10.tiff

跳转到

这给随便写一个但不要遇到下面不准用得久好

Pasted Graphic 11.tiff

然后bundle ID是比较重要的这给bundle ID 和的应用名字一值就是plist文件里面的选项要一致

Pasted Graphic 12.tiff


下面就是配置你的应用需要用的到服务

Pasted Graphic 13.tiff


最后选择“Submit”选项,在下一个界面中选择“done”选项,这样我们设置AppID的步骤我们就完成了。



这时候我们需要再创建一个ProvisioningProfile 证书了,这个证书的意思就是把上面创建的证书配置到一起的点击+(由于我们这给推送是在测试海妹呦上线,所以选择development开发证书)发布证书和这给差不多


Pasted Graphic 14.tiff

点击container 会跳转到


Pasted Graphic 15.tiff


这给ID就是你上面创建的ID点击continue跳转到

Pasted Graphic 16.tiff

这给是你的开发者账号点击continue跳转到


Pasted Graphic 17.tiff

在这一步上选择你的设备(你只有在这一步上勾选了你的设备,你才能在设备上用这个签名进行调试)。关于如何将你的设备号添加

进去也是非常简单的,选择左侧的"Devices",然后点击右上角的加号,在随后出来的页面上添加你设备的UUID(在XCode中可以查

看到)以及name( 可以随便取,自己看的懂就行)然后Register一下,照着流程走到最后一步就完成了。

好咱们继续回到上面的Provisioning Profile配置环节,当你选好了你的设备后点击“Continue”进入下一页,


Pasted Graphic 18.tiff

输入一个文件名(最好是起的能看懂是干嘛的,当然也可以随便起),点击“Generate”进入下一个页面,在这个页面中就会有一个下

载按钮让你下载这个文件,我们把它下载下来放在Push文件夹中





好了上面的证书创建都已经好了,那么我们只要在钥匙串上面把证书aps_development.cer文件


把这给文件从我们的钥匙串下面下载下来


Pasted Graphic 19.tiff




这时候我们有了3个证书分别是ps_development.cer,  push.12,certificatesingtequet.certsingningrequest以及刚才配置的文件




下面是我们在终端把这几个证书转换成pem文件

把ps_development.cer文件生产pcm文件,cd到push文件夹下

Pasted Graphic 20.tiff



把push。p12文件申城pem文件

Pasted Graphic 21.tiff


上边输入的密码则是你导出证书所设的密码,即abc123.接着还会让你输入.pem文件的密码,还是使用abc123好了,防止混淆。

这样我们在push文件夹中就又得到了两个文件,PushChatCert.pemPushChatKey.pem




pushchatcer.pem.pushchatkey.pem合并到一个文件

Pasted Graphic 22.tiff




接下来就要测试一下啦,是不是很激动~

为了测试证书工作的状况,我们可以使用“telnet gateway.sandbox.push.apple.com 2195”来检测一下,如果显示下图则表示成功了。

20141119172959109.png





然后,我们使用我们生成的证书和私钥来设置一个安全的链接去链接苹果服务器

在终端输入如下命令:openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert PushChatCert.pem -key PushChatKey.pem

需要输入密码(abc123 我们刚才所设置的)

然后他会返回一系列的数据,这里我就粘贴一部分啦:


CONNECTED(00000003)

depth=1 /C=US/O=Entrust, Inc./OU=www.entrust.net/rpa is incorporated by reference/OU=(c) 2009 Entrust, Inc./CN=Entrust Certification Authority - L1C

verify error:num=20:unable to get local issuer certificate

verify return:0

---

Certificate chain

。。。。。(省略)

。。。。。(省略)

。。。。。(省略)


    Start Time: 1416389389

    Timeout   : 300 (sec)

    Verify return code: 0 (ok)

---

测试就到这里啦。。。




第七部分

1.建立推送项目


[objc] view plaincopy


CODE_ico.png

  1. //  
  2. //  AppDelegate.m  
  3. //  TestPushNotifiy  
  4. //  
  5. //  Created by silicon on 14-10-30.  
  6. //  Copyright (c) 2014 silicon. All rights reserved.  
  7. //  
  8.   
  9. #import "AppDelegate.h"  
  10.   
  11. @implementation AppDelegate  
  12. @synthesize mainView = _mainView;  
  13.   
  14. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  15. {  
  16.     if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])  
  17.     {  
  18.         //IOS8  
  19.         //创建UIUserNotificationSettings,并设置消息的显示类类型  
  20.         UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIRemoteNotificationTypeSound) categories:nil];  
  21.           
  22.         [application registerUserNotificationSettings:notiSettings];  
  23.           
  24.     } else// ios7  
  25.         [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge                                       |UIRemoteNotificationTypeSound                                      |UIRemoteNotificationTypeAlert)];  
  26.     }  
  27.       
  28.     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  
  29.     // Override point for customization after application launch.  
  30.     self.window.backgroundColor = [UIColor whiteColor];  
  31.     [self.window makeKeyAndVisible];  
  32.       
  33.     self.mainView = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];  
  34.     self.window.rootViewController = self.mainView;  
  35.     return YES;  
  36. }  
  37.   
  38. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken{  
  39.     NSLog(@"---Token--%@", pToken);  
  40. }  
  41.   
  42. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{  
  43.       
  44.     NSLog(@"userInfo == %@",userInfo);  
  45.     NSString *message = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];  
  46.       
  47.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];  
  48.       
  49.     [alert show];  
  50. }  
  51.   
  52. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{  
  53.   
  54.     NSLog(@"Regist fail%@",error);  
  55. }  
  56.   
  57. - (void)applicationWillResignActive:(UIApplication *)application  
  58. {  
  59.     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.  
  60.     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.  
  61. }  
  62.   
  63. - (void)applicationDidEnterBackground:(UIApplication *)application  
  64. {  
  65.     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.   
  66.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
  67. }  
  68.   
  69. - (void)applicationWillEnterForeground:(UIApplication *)application  
  70. {  
  71.     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.  
  72. }  
  73.   
  74. - (void)applicationDidBecomeActive:(UIApplication *)application  
  75. {  
  76.     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.  
  77. }  
  78.   
  79. - (void)applicationWillTerminate:(UIApplication *)application  
  80. {  
  81.     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.  
  82. }  
  83.   
  84. @end  


appdelegate.m中加入以上代码,



[objc] view plaincopy


CODE_ico.png

  1. if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])  
  2.     {  
  3.         //IOS8  
  4.         //创建UIUserNotificationSettings,并设置消息的显示类类型  
  5.         UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIRemoteNotificationTypeSound) categories:nil];  
  6.           
  7.         [application registerUserNotificationSettings:notiSettings];  
  8.           
  9.     } else// ios7  
  10.         [application registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge                                       |UIRemoteNotificationTypeSound                                      |UIRemoteNotificationTypeAlert)];  
  11.     }  

由于ios8的推送跟ios7及以下的不一样,所以需要加判断来注册消息推送。

函数:


[objc] view plaincopy


CODE_ico.png

  1. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken{  
  2.     NSLog(@"---Token--%@", pToken);  
  3. }  


会接收来自苹果服务器给你返回的deviceToken,然后你需要将它添加到你本地的推送服务器上。(很重要,决定你的设备能不能接收到推送消息)。


[objc] view plaincopy


CODE_ico.png

  1. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{  
  2.       
  3.     NSLog(@"userInfo == %@",userInfo);  
  4.     NSString *message = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];  
  5.       
  6.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil nil];  
  7.       
  8.     [alert show];  
  9. }  


这个函数则是当设备接收到来自苹果推送服务器的消息时触发的,用来显示推送消息。


[objc] view plaincopy


CODE_ico.png

  1. - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{  
  2.   
  3.     NSLog(@"Regist fail%@",error);  
  4. }  

当注册失败时,触发此函数。



2.PHP服务端

simplepush.php这个推送脚本也放在push文件夹中


[php] view plaincopy


CODE_ico.png

  1. <?php  
  2.   
  3. // ??????????deviceToken???????????????  
  4. $deviceToken = 'c95f661371b085e2517b4c12cc76293522775e5fd9bb1dea17dd80fe85583b41';  
  5.   
  6. // Put your private key's passphrase here:  
  7. $passphrase = 'abc123';  
  8.   
  9. // Put your alert message here:  
  10. $message = 'My first push test!';  
  11.   
  12. ////////////////////////////////////////////////////////////////////////////////  
  13.   
  14. $ctx = stream_context_create();  
  15. stream_context_set_option($ctx'ssl''local_cert''ck.pem');  
  16. stream_context_set_option($ctx'ssl''passphrase'$passphrase);  
  17.   
  18. // Open a connection to the APNS server  
  19. //??????????  
  20.  //$fp = stream_socket_client(?ssl://gateway.push.apple.com:2195?, $err, $errstr, 60, //STREAM_CLIENT_CONNECT, $ctx);  
  21. //?????????????appstore??????  
  22. $fp = stream_socket_client(  
  23. 'ssl://gateway.sandbox.push.apple.com:2195'$err,  
  24. $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);  
  25.   
  26. if (!$fp)  
  27. exit("Failed to connect: $err $errstr" . PHP_EOL);  
  28.   
  29. echo 'Connected to APNS' . PHP_EOL;  
  30.   
  31. // Create the payload body  
  32. $body['aps'] = array(  
  33. 'alert' => $message,  
  34. 'sound' => 'default'  
  35. );  
  36.   
  37. // Encode the payload as JSON  
  38. $payload = json_encode($body);  
  39.   
  40. // Build the binary notification  
  41. $msg = chr(0) . pack('n', 32) . pack('H*'$deviceToken) . pack('n', strlen($payload)) . $payload;  
  42.   
  43. // Send it to the server  
  44. $result = fwrite($fp$msg, strlen($msg));  
  45.   
  46. if (!$result)  
  47. echo 'Message not delivered' . PHP_EOL;  
  48. else  
  49. echo 'Message successfully delivered' . PHP_EOL;  
  50.   
  51. // Close the connection to the server  
  52. fclose($fp);  
  53. ?>  

deviceToken填写你接收到的token,passPhrase则填写你的ck.pem设置的密码。

此刻就是见证奇迹的时候了,使用终端进入到push文件夹,在终端输入 php simplepush.php

20141119175631218.png













0 0
原创粉丝点击