简体   繁体   English

将iOS推送通知发送到多个设备

[英]Send iOS push notifications to multiple devices

This might be already answered but my eyes are bleeding with so much information. 这可能已经回答了,但是我的眼睛里流淌着太多的信息。 I've managed to use the notnoop notification project and is has been pretty good until the point of sending push notifications to multiple devices. 我已经设法使用了notnoop通知项目,并且在将推送通知发送到多个设备之前一直非常出色。

I'm debugging and showing the device's deviceToken through XCode and inserting it manually. 我正在调试并通过XCode显示设备的deviceToken并手动将其插入。 Obviously this is not a solution because I'm using it with the Sandbox and implementing it in delivered app is not working. 显然,这不是解决方案,因为我将其与沙盒一起使用,并且无法在交付的应用程序中实现它。

So now is where I'm asking myself how to "automatize" the process of registering the device's deviceTokens on the server and sending the push notification message to all of them. 因此,现在是我问自己如何在服务器上注册设备的deviceToken并将推送通知消息发送给所有人的过程“自动化”的地方。

I've been thinking on creating a .jsp and passing the deviceTokens through POST, make an INSERT on the MySQL database and then, when wanting to send a push notification, pick up every deviceToken and then send the push notifications. 我一直在考虑创建.jsp并通过POST传递deviceTokens,在MySQL数据库上进行INSERT,然后,当要发送推送通知时,选择每个deviceToken,然后发送推送通知。

I can't believe this isn't already explained anywhere or maybe I'm too confused at this point to see it. 我不敢相信这还没有在任何地方解释过,或者我现在很困惑以至于看不到它。

Actually, my code is the following: 实际上,我的代码如下:

import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsService;

public class PushServiceTryout
{
    public static void main(String[] args)
    {
        ApnsService service = APNS.newService()
                .withCert("c:/fcertificates.p12", "1234")
                .withSandboxDestination()
                .build();
        String msg = "Hello! Push notification test!";          
        String payload = APNS.newPayload().alertBody(msg).build();
        //Obviously fake
        String token = "123456789012345678901234567890abcabcabcacbabcbacbacb";
        service.push(token, payload);
        System.out.println("Notification sent");
    }
}

Any ideas? 有任何想法吗? Thank you so much in advance. 提前非常感谢您。

I finally did this in .jsp. 我终于在.jsp中做到了。 Here it is the source if anyone needs it: 如果有人需要,这里是来源:

Index.jsp Index.jsp

<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
    System.out.println(" *** DEBUG *** On push notifications -menu- \n");

    Connection conn = null;
    Statement statement = null;
    ResultSet resultSet = null;

    // Connection parameters
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/apns";
    String user = "root";
    String passwd = "";

    // ******** Connection procedure ********
    String connectionstatus="";
    try
    {
        Class.forName(driver);
        conn = DriverManager.getConnection(url,user,passwd);
    } catch (Exception ex){
        connectionstatus=ex.toString();
    }
    connectionstatus="connected to the DB!";
    if(conn.isClosed())
    {
        connectionstatus="NOT connected to the DB. Check URL, DB connectivity...";
    }
    //******** END of the connetion procedure ********

    statement = conn.createStatement();

    // ******** TABLE with inserted deviceTokens on the DB ********
    String querytotal="SELECT * from devicetokens";
    resultSet = statement.executeQuery(querytotal);

    out.println("The following DeviceTokens are saved on the DB: " + "<BR>");
    out.println("<table border=2>");
    while(resultSet.next())
    {
        out.println("<tr>");
        out.println("<td>" + resultSet.getString("id") + "</td>");
        out.println("<td>" + resultSet.getString("devicetoken") + "</td>");
        out.println("</tr>");
        System.out.println(" *** DEBUG *** " + resultSet.getString("id") + " -> " + resultSet.getString("devicetoken"));
    }
    out.println("</table>");
    // ******** END of the table with saved deviceTokens ********

    // ------> Receiving the deviceToken from the device! <------
    String devtoken = request.getParameter("devtoken");

    boolean flag = false;
    if(devtoken == null)
    {
        System.out.println("Just reloaded the page? Recently running the server? Because no devtoken has been received.");
        flag = true;    // Prevents inserting a "null" devtoken into the DB. FLAG up
    }
    else
    {
        System.out.println("The received deviceToken is: " + devtoken);
        // Insert deviceToken into the DB
        String queryinsert="INSERT INTO devicetokens(devicetoken) VALUES ('" + devtoken + "')";
        statement = conn.createStatement();
        statement.execute(queryinsert);

        // Show inserted deviceTokens on the DB
        String queryshow="SELECT * from devicetokens";
        resultSet = statement.executeQuery(queryshow);
    }
%>
<html>
    <head>
        <title>Push menu</title>
    </head>
    <body>
        <!-- Show if you're connected to the database or not -->
        <h1>You are <%=connectionstatus%></h1>
        <form action="sendpush.jsp" method="POST">
            <label><b>.p12 certificate</b> path</label> <input type="file" name="path"> <br>
            <label> Certificate password</label> <input type="text" name="password"> <br>
            <!-- Offer the a textarea for the user and handle the maxlength -->
            <label>Message to be sent:</label> <input type="text" name="message" size="60" maxlength="110" onkeyup="total.value = 110 - this.value.length">
                <input type="text" name="total" size="3" maxlength="3" disabled>
            <input type="submit" value="Send push notification"/>
        </form>
    </body>
</html>

sendpush.jsp sendpush.jsp

<%@page import="java.sql.*,com.notnoop.apns.APNS,com.notnoop.apns.ApnsService,java.util.List,java.util.ArrayList,java.util.Iterator"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
    System.out.println(" *** DEBUG *** On sending push notifications \n");

// ************ APNS settings **************
    String cpath = request.getParameter("path");    // Path with the located .p12 file
    String cpasswd = request.getParameter("password");  // Certificate's password

    ApnsService service = APNS.newService()
    .withCert("c:/fcertificates.p12", "1234")
    // In case we're on developer environment use .withSandboxdestination()
    .withSandboxDestination()
    // In case we're on production environment (final app ready to be delivered on the App Store) use .withProductionDestination()
    //.withProductionDestination()
    .build();

    String msg = request.getParameter("message");   // Message that user wants to deliver to devices    
    String payload = APNS.newPayload()
    .alertBody(msg)
    .badge(0)
    .sound("default")
    .build();   

// ***************** END of APNS settings ***************
    Connection conn = null;
    Statement statement = null;
    ResultSet resultSet = null;

    // Connection parameters
    String driver = "com.mysql.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/apns";
    String user = "root";
    String passwd = "";

    // ******** Connection procedure ********
    String message="";
    try
    {
        Class.forName(driver);
        conn = DriverManager.getConnection(url,user,passwd);
    } catch (Exception ex){
        message=ex.toString();
    }

    message="Connected!";
    if(conn.isClosed()){
        message="Disconnected";
    }
    //******** END of the connetion procedure ********

    // Executing the query
    statement = conn.createStatement();

    // Retrieve all the deviceTokens from DB
    String queryshow = "SELECT devicetoken from devicetokens";
    resultSet = statement.executeQuery(queryshow);

    List<String> listtokens = new ArrayList<String>();  // A List<> to play with the deviceTokens

    while(resultSet.next())
    {
        out.println("A push notification is going to be sent to the following devicetoken " + resultSet.getString("devicetoken") + "<BR>"); // Show the deviceToken
        listtokens.add(resultSet.getString("devicetoken")); // Add it to the List of deviceTokens
        System.out.println(" *** DEBUG *** Added " + resultSet.getString("devicetoken") + " to the List<>");    // Show in console
    }

%>
<html>
    <head>
        <title>Notification sent...</title>
    </head>
    <body>        
        <%
        Iterator it = listtokens.iterator();
        while(it.hasNext()) // Send the push notification to the deviceTokens on the List<> 
        {
            String finaltoken = (String)it.next();
            service.push(finaltoken, payload);
            out.println("Push notification sent to devicetoken: " + finaltoken + "<BR>");
            System.out.println(" *** DEBUG *** Push notification sent to devicetoken: " + finaltoken);
        }
        %>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM