4、PushTest.p12
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSString *token = [NSString stringWithFormat:@"%@", deviceToken];//获取终端设备标识,这个标识需要通过接口发送到服务器端,服务器端推送消息到APNS时需要知道终端的标识,APNS通过注册的终端标识找到终端设备。NSLog(@"My token is:%@", token); } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSString *error_str = [NSString stringWithFormat: @"%@", error]; NSLog(@"Failed to get token, error:%@", error_str); }
2、在AppDelegate.m的(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中加入注册消息通知推送能力;加入当应用程序处于未启动状态时,判断是否由远程消息通知触发;加入清除消息推送通知标记。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {//判断是否由远程消息通知触发应用程序启动if ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]!=nil) {//获取应用程序消息通知标记数(即小红圈中的数字)int badge = [UIApplication sharedApplication].applicationIconBadgeNumber;if (badge>0) {//如果应用程序消息通知标记数(即小红圈中的数字)大于0,清除标记。badge--;//清除标记。清除小红圈中数字,小红圈中数字为0,小红圈才会消除。[UIApplication sharedApplication].applicationIconBadgeNumber = badge;}}//消息推送注册[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge]; } 3、在项目AppDelegate.m中加入消息接收处理代理方法。 //处理收到的消息推送 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {//在此处理接收到的消息。NSLog(@"Receive remote notification : %@",userInfo); }
六、JAVA后台代码:
public static void main(String[] args) throws Exception {try{//从客户端获取的deviceToken,在此为了测试简单,写固定的一个测试设备标识。String deviceToken = "df779eda 73258894 5882ec78 3ac7b254 6ebc66fe fa295924 440d34ad 6505f8c4"System.out.println("Push Start deviceToken:" + deviceToken);//定义消息模式PayLoad payLoad = new PayLoad();payLoad.addAlert("this is test!");payLoad.addBadge(1);//消息推送标记数,小红圈中显示的数字。payLoad.addSound("default");//注册deviceTokenPushNotificationManager pushManager = PushNotificationManager.getInstance();pushManager.addDevice("iPhone", deviceToken);//连接APNSString host = "gateway.sandbox.push.apple.com";//String host = "gateway.push.apple.com";int port = 2195;String certificatePath = "c:/PushTest.p12";//前面生成的用于JAVA后台连接APNS服务的*.p12文件位置String certificatePassword = "123456";//p12文件密码。pushManager.initializeConnection(host, port, certificatePath, certificatePassword, SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);//发送推送Device client = pushManager.getDevice("iPhone");System.out.println("推送消息: " + client.getToken()+"\n"+payLoad.toString() +" ");pushManager.sendNotification(client, payLoad);//停止连接APNSpushManager.stopConnection();//删除deviceTokenpushManager.removeDevice("iPhone");System.out.println("Push End");}catch (Exception ex){ex.printStackTrace();} } }