iOS推送的那些事

2025-05-29 0 59

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

iOS推送的那些事

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 有可能会更改,因此需要在程序每次启动时都去注册并且上传到你的服务器端。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59
- (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得到消息内容

?

1

2

3

4

5

6

7

8
- (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions {

//...

nsdictionary *payload = [launchoptions objectforkey:uiapplicationlaunchoptionsremotenotificationkey];

if (payload) {

//...

}

//...

}

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21
- (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为例):

?

1

2

3

4

5
{

  "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,心里早就称呼你“死前段”多年了,还那么多事……
所以关于调试推送,这里有两种方式实现自推!不麻烦别人。
模拟推送通过终端推送

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39
<?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
两个文件放在同一目录
执行下面的命令

?

1
superdanny@superdannydemacbook-pro$ php push.php

结果为

?

1

2
connected to apns

message successfully delivered

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS推送的那些事 https://www.kuaiidc.com/93919.html

相关文章

发表评论
暂无评论