所以我正在努力进行推送通知,并且遵循了本教程,并且能够成功地将Firebase项目的推送通知发送到我的手机。现在,我试图将发送消息传递到设备组,如本Google教程所示。
现在,我使用此方法获得了设备令牌:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("deviceToken: (tokenString)")
}
我试图将其添加到设备组(在服务器端(,例如:
public static String addDeviceToGroup(String userKeyName, List<String> deviceToken, String notificationKey) throws IOException, JSONException {
String result = "";
URL url = new URL(API_URL_FCM_GROUP);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("project_id", SENDER_ID);
JSONObject json = new JSONObject();
json.put("registration_ids",deviceToken);
json.put("operation","add");
json.put("notification_key_name",userKeyName.trim());
json.put("notification_key",notificationKey.trim());
try {
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(json.toString());
wr.flush();
int responseCode = conn.getResponseCode();
System.out.print("RESPONSE CODE in addDeviceToGroup IS: " + responseCode + "n");
BufferedReader br = null;
if (responseCode == 200)
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
else
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String output;
System.out.println("Output from Server .... n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
result = SUCCESS;
} catch (Exception e) {
e.printStackTrace();
result = FAILURE;
}
System.out.println("FCM Notification added device to group successfully RESULT IS " + result);
return result;
}
我一直将400作为响应代码,并且我继续遇到此错误:
{"error":"no valid registration ids"}
尝试从设备组删除时也会遇到相同的错误。
编辑:但是,当我获得该令牌时:
let secondToken = InstanceID.instanceID().token()!
成功将令牌添加到设备组中,当我将用户MSG发送到属于设备的通知密钥时,在我的控制台中显示了它已交付:
{"success":2,"failure":0}
但不会在我的设备上弹出。
任何帮助将不胜感激。
我不知道您是否仍然需要帮助,但是为了摆脱错误,您必须将DeviceToken放在数组中。
let postparameters = ["operation": "create",
"notification_key_name": name,
"registration_ids": [devicetoken]] as [String : Any]