向多个设备发送 iOS 推送通知

Posted

技术标签:

【中文标题】向多个设备发送 iOS 推送通知【英文标题】:Send iOS push notifications to multiple devices 【发布时间】:2014-11-24 14:17:59 【问题描述】:

这可能已经被回答了,但我的眼睛因太多的信息而流血。我已经设法使用了 notnoop 通知项目,并且在向多个设备发送推送通知之前一直很好。

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

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

我一直在考虑创建一个 .jsp 并通过 POST 传递 deviceToken,在 mysql 数据库上进行 INSERT,然后,当想要发送推送通知时,获取每个 deviceToken,然后发送推送通知。

我不敢相信这在任何地方都没有得到解释,或者我现在太困惑了,看不到它。

其实我的代码如下:

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

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

【问题讨论】:

好吧,您可以自己编写一个服务器,从您的设备中获取令牌。或者,您可以使用为您完成此任务的服务(如 Boxcar、Urban Airship 等)。 谢谢。我终于制作了两个等待并处理这个问题的.jsp。我将代码粘贴在这里。无论如何,谢谢, 【参考方案1】:

我终于在 .jsp 中做到了。如果有人需要,这里是来源:

索引.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>

【讨论】:

"It's not the best code in the world but hope you enjoy it." 可能不是您要添加的评论,所以我已删除 你的jar文件在同一个文件夹吗?我收到此错误,只能导入一个类型。 com.notnoop.apns.ApnsService 解析为一个包

以上是关于向多个设备发送 iOS 推送通知的主要内容,如果未能解决你的问题,请参考以下文章

从 php 服务器向 ios 设备发送多个推送通知

如何在一个请求中向多个设备(iOS)发送推送通知?

我们可以从 iOS 设备向 APNs 发送推送通知吗?

Azure 向多个设备/广播发送推送通知

使用 php 向 IOS 设备发送推送通知

Web 应用程序如何向 iOS 设备发送推送通知? [关闭]