iOS推送的那些事


直接切入主题,讲讲如何模拟推送以及处理推送消息。在进入主题之前,我先说几个关键流程:
1、建Push SSL Certification(推送证书)
2、OS客户端注册Push功能并获得DeviceToken
3、用Provider向APNS发送Push消息
4、OS客户端接收处理由APNS发来的消息
推送流程图:

Provider:就是为指定iOS设备应用程序提供Push的服务器。如果iOS设备的应用程序是客户端的话,那么Provider可以理解为服务端(推送消息的发起者)
APNs:Apple Push Notification Service(苹果消息推送服务器)
Devices:iOS设备,用来接收APNs下发下来的消息
Client App:iOS设备上的应用程序,用来接收APNs下发的消息到指定的一个客户端app(消息的最终响应者)
1、取Device token
App 必须要向 APNs 请求注册以实现推送功能,在请求成功后,APNs 会返回一个设备的标识符即 DeviceToken 给 App,服务器在推送通知的时候需要指定推送通知目的设备的 DeviceToken。在 iOS 8 以及之后,注册推送服务主要分为四个步骤:

  • 使用 registerUserNotificationSettings:注册应用程序想要支持的推送类型
  • 通过调用 registerForRemoteNotifications方法向 APNs 注册推送功能
  • 请求成功时,系统会在应用程序委托方法中返回 DeviceToken,请求失败时,也会在对应的委托方法中给出请求失败的原因。
  • 将 DeviceToken 上传到服务器,服务器在推送时使用。

上述第一个步骤注册的 API 是 iOS 8 新增的,因此在 iOS 7,前两个步骤需更改为 iOS 7 中的 API。
DeviceToken 有可能会更改,因此需要在程序每次启动时都去注册并且上传到你的服务器端。

- (BOOL)application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    NSLog(@"Requesting permission for push notifications..."); // iOS 8
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:
      UIUserNotificationTypeAlert | UIUserNotificationTypeBadge |
      UIUserNotificationTypeSound categories:nil];
    [UIApplication.sharedApplication registerUserNotificationSettings:settings];
  } else {
    NSLog(@"Registering device for push notifications..."); // iOS 7 and earlier
    [UIApplication.sharedApplication registerForRemoteNotificationTypes:
      UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |
      UIRemoteNotificationTypeSound];
  }
  return YES;
}

- (void)application:(UIApplication *)application
  didRegisterUserNotificationSettings:(UIUserNotificationSettings *)settings
{
  NSLog(@"Registering device for push notifications..."); // iOS 8
  [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application
  didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)token
{
  NSLog(@"Registration successful, bundle identifier: %@, mode: %@, device token: %@",
    [NSBundle.mainBundle bundleIdentifier], [self modeString], token);
}

- (void)application:(UIApplication *)application
  didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  NSLog(@"Failed to register: %@", error);
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier
  forRemoteNotification:(NSDictionary *)notification completionHandler:(void(^)())completionHandler
{
  NSLog(@"Received push notification: %@, identifier: %@", notification, identifier); // iOS 8
  completionHandler();
}

- (void)application:(UIApplication *)application
  didReceiveRemoteNotification:(NSDictionary *)notification
{
  NSLog(@"Received push notification: %@", notification); // iOS 7 and earlier
}

- (NSString *)modeString
{
#if DEBUG
  return @"Development (sandbox)";
#else
  return @"Production";
#endif
}

2、处理推送消息
1)、程序未启动,用户接收到消息。需要在AppDelegate中的didFinishLaunchingWithOptions得到消息内容

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  //...
  NSDictionary *payload = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
  if (payload) {
    //...
  }
  //...
}

2)、程序在前台运行,接收到消息不会有消息提示(提示框或横幅)。当程序运行在后台,接收到消息会有消息提示,点击消息后进入程序,AppDelegate的didReceiveRemoteNotification函数会被调用,消息做为此函数的参数传入

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)payload {
  NSLog(@"remote notification: %@",[payload description]);
  NSString* alertStr = nil;    
  NSDictionary *apsInfo = [payload objectForKey:@"aps"];  
  NSObject *alert = [apsInfo objectForKey:@"alert"];  
  if ([alert isKindOfClass:[NSString class]])  
  {    
    alertStr = (NSString*)alert;  
  }  
  else if ([alert isKindOfClass:[NSDictionary class]])  
  {    
    NSDictionary* alertDict = (NSDictionary*)alert;    
    alertStr = [alertDict objectForKey:@"body"];  
  }    
  application.applicationIconBadgeNumber = [[apsInfo objectForKey:@"badge"] integerValue];    
  if ([application applicationState] == UIApplicationStateActive && alertStr != nil)  
  {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Pushed Message" message:alertStr delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];  
  }
}

3、义通知提示音
你可以在 App 的 Bundle 中加入一段自定义提示音文件。然后当通知到达时可以指定播放这个文件。必须为以下几种数据格式:

  • Linear PCM
  • MA4(IMA/ADPCM)
  • μLaw
  • aLaw

你可以将它们打包为aiff、wav或caf文件。自定义的声音文件时间必须小于 30秒,如果超过了这个时间,将被系统声音代替。
4、Payload
Payload 是通知的一部分,每一条推送通知都包含一个 Payload。它包含了系统提醒用户通知到达的方式,还可以添加自定义的数据。即通知主要传递的数据为 Payload。
Payload 本身为 JSON 格式的字符串,它内部必须要包含一个键为 aps 的字典。aps 中可以包含以下字段中的一个或多个:
alert:其内容可以为字符串或者字典,如果是字符串,那么将会在通知中显示这条内容
badge:其值为数字,表示当通知到达设备时,应用的角标变为多少。如果没有使用这个字段,那么应用的角标将不会改变。设置为 0 时,会清除应用的角标。
sound:指定通知展现时伴随的提醒音文件名。如果找不到指定的文件或者值为 default,那么默认的系统音将会被使用。如果为空,那么将没有声音。
content-available:此字段为 iOS 7 silent remote notification 使用。不使用此功能时无需包含此字段。
如果需要添加自定义的字段,就让服务器的小伙伴们跟aps同一层级添加一个数组(以Json为例):

{
  "aps" : {"alert" : "This is the alert text", "badge" : 1, "sound" :"default" },

  "server" : {"serverId" : 1, "name" : "Server name"}
}

这样收到的 Payload 里面会多一个 server 的字段。
5、模拟推送
现在常用的后台server中,一般将推送证书以及推送证书的私钥导出p12交给后台人员即可。
生成PHP需要的Pem证书
6、PHP有点调皮,还需要转换成pem
准备:
1)、苹果服务器证书端设置正确!打包证书、描述文件正确!!
2)、下载推送证书(cer格式),导入keyChain,保证私钥存在,不存在去找创建这个证书的电脑要一份过来。
3)、从钥匙库导出的~~根证书~~(推送证书)私钥(p12格式)
第三步根证书的私钥这里是一个坑!因为一个App的推送证书的创建可以和根证书创建的电脑不同,也就是keyChain产生的certSigningRequest不一样,所以私钥也是不一样的,在这里生成Pem时,注意要使用推送证书的私钥!
操作过程:
A.把推送证书(.cer)转换为.pem文件,执行命令:
openssl x509 -in 推送证书.cer -inform der -out 推送证书.pem
B.把推送证书导出的私钥(.p12)文件转化为.pem文件:
openssl pkcs12 -nocerts -out 推送证书私钥.pem -in 推送证书私钥.p12 
C.对生成的这两个pem文件再生成一个pem文件,来把证书和私钥整合到一个文件里:
cat 推送证书.pem 推送证书私钥.pem >PHPPush.pem
然后把这个PHPPush.pem给后台基友们,就可以下班啦。
当然测试推送也比较麻烦,需要模拟真实的推送环境,一般需要后台提供帮助,但是遇到一些后台同事,他们有强烈地信仰着鄙视链的话,很鄙视iOS,心里早就称呼你“死前段”多年了,还那么多事……
所以关于调试推送,这里有两种方式实现自推!不麻烦别人。
模拟推送:通过终端推送

<?php
// devicetoken
 $deviceToken = '你的deviceToken';
// 私钥密码,生成pem的时候输入的
$passphrase = '123456';
// 定制推送内容,有一点的格式要求,详情Apple文档
$message = array(
  'body'=>'你收到一个新订单'
);
$body['aps'] = array(
  'alert' => $message,
  'sound' => 'default',
  'badge' => 100,
  );
$body['type']=3;
$body['msg_type']=4;
$body['title']='新订单提醒';
$body['msg']='你收到一个新消息';

$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'push.pem');//记得把生成的push.pem放在和这个php文件同一个目录
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client(
  //这里需要特别注意,一个是开发推送的沙箱环境,一个是发布推送的正式环境,deviceToken是不通用的
  'ssl://gateway.sandbox.push.apple.com:2195', $err,
  //'ssl://gateway.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;
$payload = json_encode($body);
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
  echo 'Message not delivered' . PHP_EOL;
else
  echo 'Message successfully delivered' . PHP_EOL;
fclose($fp);
?>

将上面的代码复制,保存成push.php
然后根据上面生成PHP需要的Pem证书的步骤生成push.pem
两个文件放在同一目录
执行下面的命令

superdanny@SuperDannydeMacBook-Pro$ php push.php 

结果为

Connected to APNS
Message successfully delivered

以上就是关于IOS推送的那些事,希望对大家的学习有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3