<dependency>
<groupId>com.eatthepath</groupId>
<artifactId>pushy</artifactId>
<version>0.15.0</version>
</dependency>
@Slf4j
@Component
public class APNUtil {
private static ApnsClient apnsClient = null;
private static final String p12Password = "123456";
public static PushNotificationResponse<SimpleApnsPushNotification> ApplePush(String deviceToken, String topic, String alert, int badge, Long time, DeliveryPriority priority, PushType pushType) throws ExecutionException, InterruptedException {
Date invalidationTime = new Date(System.currentTimeMillis() + time);
Instant instant = invalidationTime.toInstant();
Map<String,Object> body = new HashMap<>();
body.put("alert",alert);
body.put("badge",badge);
body.put("sound","default");
Map<String,Object> apns = new HashMap<>();
apns.put("aps",body);
String payload = JSON.toJSONString(apns);
SimpleApnsPushNotification msg = new SimpleApnsPushNotification(deviceToken, topic, payload, instant, priority, pushType);
PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> future = getAPNSConnect().sendNotification(msg);
PushNotificationResponse<SimpleApnsPushNotification> response = future.get();
return response;
}
public static ApnsClient getAPNSConnect() {
if (apnsClient == null) {
try {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
String resourceLocation = null;
resourceLocation = "src/main/resources/templates/callMessageAPNs.p12";
File file = ResourceUtils.getFile(resourceLocation);
if (file.exists()) {
log.info("文件存在");
}
apnsClient = new ApnsClientBuilder()
.setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
.setClientCredentials(file, p12Password)
.setConcurrentConnections(4)
.setEventLoopGroup(eventLoopGroup).build();
} catch (Exception e) {
e.printStackTrace();
log.error("Get IOS Connect Exception, Please Check:{}", e.getMessage());
}
}
return apnsClient;
}
public static void sendIosMsg(String deviceToken, String msgBody, int badge) {
PushNotificationResponse<SimpleApnsPushNotification> response = null;
try {
response = APNUtil.ApplePush(deviceToken, "com.gmyd.calltest", msgBody,badge,60 * 1000L, DeliveryPriority.IMMEDIATE, PushType.ALERT);
} catch (Exception e) {
e.printStackTrace();
log.error("Ios Send Msg Fail{}",e.getMessage());
return;
}
log.info("执行结果:{}",response.getRejectionReason());
log.info("如果返回的消息中success为true那么成功,否则失败!{}", JSON.toJSONString(response));
}
}