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

时间:2014-11-24 14:18:00

标签: ios push-notification apple-push-notifications

这可能已经得到了解答但是我的眼睛因为这么多信息而流血。我已经设法使用 notnoop 通知项目,并且在向多个设备发送推送通知之前一直非常好。

我正在调试并通过XCode显示设备的deviceToken并手动插入。显然这不是一个解决方案,因为我在Sandbox中使用它并在交付的应用程序中实现它不起作用。

所以现在我问自己如何“自动化”在服务器上注册设备的deviceTokens并向所有人发送推送通知消息的过程。

我一直在考虑创建一个.jsp并通过POST传递deviceTokens,在MySQL数据库上创建一个INSERT然后,当想要发送推送通知时,拿起每个deviceToken,然后发送推送通知。 / p>

我无法相信这在任何地方都没有解释过,或者我现在太困惑了。

实际上,我的代码如下:

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");
    }
}

有什么想法吗?非常感谢你。

1 个答案:

答案 0 :(得分:0)

我终于在.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

<%@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>