iOS APNS推送遠端訊息 java後臺實現

曉章同學發表於2018-01-10

準備工作之前得準備三個檔案:一個是CSR請求檔案(CertificateSigningRequest)、一個是aps_development.cer的SSL證照檔案、還有一個是推送的PushDeveloper.p12祕鑰檔案。如下圖所示:

iOS APNS推送遠端訊息 java後臺實現

1.生成Certificate Signing Request步驟省略。

2.下載開發證照和釋出證照

到蘋果開發官網描述下載證照,以開發證照為案例。如下圖所示:

iOS APNS推送遠端訊息 java後臺實現

3.從鑰匙串訪問中匯出金鑰

開啟鑰匙串訪問,找到我們的專用金鑰(專用祕鑰就是我們下載推送證照安裝本地的私人金鑰),如下圖所示:

iOS APNS推送遠端訊息 java後臺實現

匯出.p12檔案的時候需要輸入密碼,我這裡選擇簡單點為123456,這密碼需要記住,後面有用到。

iOS APNS推送遠端訊息 java後臺實現

上面步驟完成後開啟終端 cd到p12目錄,就是放那三個檔案所在的資料夾目錄

1.把aps_development.cer的SSL證照轉換為PushChatCert.pem檔案,執行命令:

openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem
複製程式碼

iOS APNS推送遠端訊息 java後臺實現

在p12目錄下會生成一個PushChatCert.pem檔案

2.把PushDeveloper.p12格式的私鑰轉化成PushChatKey.pem,需要設定密碼,密碼為abc123

openssl pkcs12 -nocerts -out PushChatKey.pem -in PushDeveloper.p12
複製程式碼

iOS APNS推送遠端訊息 java後臺實現

3.用certificate和PushChatKey.pem建立apns_developer_identity.p12檔案(java後臺配置用到的),需要輸入密語:abc123

openssl pkcs12 -export -in PushChatCert.pem -inkey PushChatKey.pem -certfile CertificateSigningRequest.certSigningRequest -name "apns_developer_identity" -out apns_developer_identity.p12
複製程式碼

iOS APNS推送遠端訊息 java後臺實現

ios工程測試

在AppDelegate裡didFinishLaunchingWithOptions函式裡寫

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                             categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }else{
        //這裡還是原來的程式碼
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }
    return YES;
}
 
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
      NSLog(@"regisger success:%@", [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""] stringByReplacingOccurrencesOfString:@">"withString:@""]stringByReplacingOccurrencesOfString:@" "withString:@""]);
}

//前臺收到訊息
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    // 處理推送訊息
    NSLog(@"userinfo:%@",userInfo);
    
    NSLog(@"收到推送訊息:%@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"Registfail%@",error);
    NSLog(@"DeviceToken獲取失敗,原因:%@",error);
}
複製程式碼

java後臺程式碼

public static void main(String[] args) throws Exception{

        int badge = 1; // 圖示小紅圈的數值
        String sound = "default"; // 鈴音
        String msgCertificatePassword = "123456";//匯出證照時設定的密碼
                            //90fb73e94659a1822caa51ca079734de6a7e60e44f260a1bfd1326bb4648d734
        String deviceToken = "a1f52f971ca720d6ffc98ce7212c74edf347234ab2cc34fefcb541314e2e13e1"; //手機裝置token號
        String message = "test push message to ios device11111111111";

        List<String> tokens = new ArrayList<String>();
        tokens.add(deviceToken);

        //java必須要用匯出p12檔案  php的話是pem檔案
        String certificatePath = "/Users/xxxx/Desktop/p12/apns_developer_identity.p12";
        boolean sendCount = true;

        PushNotificationPayload payload = new PushNotificationPayload();
        payload.addAlert(message); // 訊息內容
        payload.addBadge(badge);


        //payload.addCustomAlertBody(msgEX);
        if (null == sound || "".equals(sound)) {
            payload.addSound(sound);
        }

        PushNotificationManager pushManager = new PushNotificationManager();
        // false:表示的是產品測試推送服務 true:表示的是產品釋出推送服務
        pushManager.initializeConnection(new AppleNotificationServerBasicImpl(
                certificatePath, msgCertificatePassword, false));
        List<PushedNotification> notifications = new ArrayList<PushedNotification>();
        // 開始推送訊息
        if (sendCount) {
            Device device = new BasicDevice();
            device.setToken(deviceToken);
            PushedNotification notification = pushManager.sendNotification(
                    device, payload, true);
            notifications.add(notification);
        } else {
            List<Device> devices = new ArrayList<Device>();
            for (String token : tokens) {
                devices.add(new BasicDevice(token));
            }
            notifications = pushManager.sendNotifications(payload, devices);
        }

        List<PushedNotification> failedNotification = PushedNotification
                .findFailedNotifications(notifications);
        List<PushedNotification> successfulNotification = PushedNotification
                .findSuccessfulNotifications(notifications);
        int failed = failedNotification.size();
        int successful = successfulNotification.size();
        System.out.println("zsl==========成功數:" + successful);
        System.out.println("zsl==========失敗數:" + failed);
        pushManager.stopConnection();
        System.out.println("zsl==========訊息推送完畢");
    }
複製程式碼

您的pom.xml新增以下依賴項:

     <dependency>
           <groupId>com.github.fernandospr</groupId>
           <artifactId>javapns-jdk16</artifactId>
           <version>2.3.1</version>
       </dependency>
       <dependency>
           <groupId>log4j</groupId>
           <artifactId>log4j</artifactId>
           <version>1.2.17</version>
       </dependency>
複製程式碼

相關文章