ios推送–apns
文章目录
前言
- 使用极光推送或友盟推送在ios上只能推送普通的信息,普通推送在用户点击通知栏时这时才唤醒app,于是看到app从启动页开始加载,这对于一些场景下可能不适用,比如我想在点击时就可以马上显示想要的画面,在做语音通话时这点显得比较重要
- 普通推送是做不到了,callkit在中国又是被禁的,那么就只剩下VOIP了
- 但VOIP需要证书这点还是比较麻烦的,搞到证书后要通过苹果审核也只能看运气了(详见 iOS审核被拒大全:https://www.cnblogs.com/YolvinBlog/p/6296091.html)
准备
- 向苹果申请pc12格式的证书(一年有效,到期需重新申请)
步骤
添加依赖
-
以下以gradle方式示例
// https://mvnrepository.com/artifact/com.turo/pushy compile group: 'com.turo', name: 'pushy', version: '0.13.7'
获得ApnsClient
-
通过设置证书和密码获得ApnsClient对象
//证书路径 Resource resource = new ClassPathResource("static/ACS_Landlord_VoIP_2019-03-14.p12"); File file = resource.getFile(); final ApnsClient apnsClient = new ApnsClientBuilder() .setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST) //生产环境还是开发环境 .setClientCredentials(file, "123456") //证书密码 .build();
-
其中ApnsClientBuilder.DEVELOPMENT_APNS_HOST表示在测试环境中使用,假如ios使用的是生产环境,那么则要改为ApnsClientBuilder.PRODUCTION_APNS_HOST,否则推送会失败
推送
- 获得设备码后开始推送
final SimpleApnsPushNotification pushNotification;
final String token = TokenUtil.sanitizeTokenString("9e3a8da155d97e14ab459923d8992bf48e2807a4defb9517d6534311c82c1d57");
pushNotification = new SimpleApnsPushNotification(token, "com.xxx.xxx.voip", "这是推送内容");
final PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>>
sendNotificationFuture = apnsClient.sendNotification(pushNotification);
try {
final PushNotificationResponse<SimpleApnsPushNotification> pushNotificationResponse =
sendNotificationFuture.get();
if (pushNotificationResponse.isAccepted()) {
System.out.println("Push notification accepted by APNs gateway.");
} else {
System.out.println("Notification rejected by the APNs gateway: " +
pushNotificationResponse.getRejectionReason());
if (pushNotificationResponse.getTokenInvalidationTimestamp() != null) {
System.out.println("\t…and the token is invalid as of " +
pushNotificationResponse.getTokenInvalidationTimestamp());
}
}
} catch (final ExecutionException e) {
System.err.println("Failed to send push notification.");
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
- 其中的token则是ios的设备码,topic则应用的bundle id加上后缀.voip,比如bundle id为com.xxx.xxx,那么则填写com.xxx.xxx.voip
- 更多用法请详看 https://github.com/relayrides/pushy
参考
relayrides/pushy: A Java library for sending APNs (iOS/macOS/Safari) push notifications
https://github.com/relayrides/pushy
notnoop/java-apns: Java Apple Push Notification Service Provider
https://github.com/notnoop/java-apns