我必须在iOS设备上发送pkPasses的推送通知。
I have found a code on git hub.
使用 SendEmptyPushNotification 方法发送推送通知。我正在为 deviceIdentifier 发送PushToken 但它不起作用。有时这段代码需要花费太多时间,有时甚至需要时间。但在这两种情况下我都无法在我的iOS设备上获得任何推送通知。我真的卡在这里任何人都可以帮忙??
public class IPhonePushNotificationService
{
public void SendEmptyPushNotification(string deviceIdentifier, string thumbprint)
{
string server = "gateway.push.apple.com";
using (TcpClient tcpClient = new TcpClient(server, 2195))
{
Trace.TraceInformation("Opening SSL Connection...");
using (SslStream sslStream = new SslStream(tcpClient.GetStream()))
{
try
{
X509Certificate2Collection certs = new X509Certificate2Collection();
Trace.TraceInformation("Adding certificate to connection...");
X509Certificate cert = GetAppleServerCert(thumbprint);
certs.Add(cert);
Trace.TraceInformation("Authenticating against the SSL stream...");
sslStream.AuthenticateAsClient(server, certs, SslProtocols.Default, false);
}
catch (AuthenticationException exp)
{
Trace.TraceError("Failed to authenticate to APNS - {0}", exp.Message);
return;
}
catch (IOException exp)
{
Trace.TraceError("Failed to connect to APNS - {0}", exp.Message);
return;
}
byte[] buf = new byte[256];
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32 });
byte[] deviceToken = HexToData(deviceIdentifier);
bw.Write(deviceToken);
string msg = "{}";
bw.Write(new byte[] { 0, 2 });
bw.Write(msg.ToCharArray());
bw.Flush();
Trace.TraceInformation("Message sent. Closing stream...");
if (sslStream != null)
{
sslStream.Write(ms.ToArray());
}
byte[] response = new byte[6];
sslStream.Read(response, 0, 6);
sslStream.Flush();
}
}
}
private static X509Certificate GetAppleServerCert(string thumbprint)
{
X509Store store;
store = new X509Store(StoreLocation.CurrentUser);
if (store != null)
{
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates;
if (certs.Count > 0)
{
for (int i = 0; i < certs.Count; i++)
{
X509Certificate2 cert = certs[i];
if (cert.Thumbprint.Equals(thumbprint, StringComparison.InvariantCultureIgnoreCase))
{
return certs[i];
}
}
}
}
Trace.TraceError("Could not find the certification containing: {0} ", "R5QS56362W:R5QS56362W");
throw new InvalidDataException("Could not find the Apple Push Notification certificate");
}
private static byte[] HexToData(string hexString)
{
if (hexString == null)
{
return null;
}
if (hexString.Length % 2 == 1)
{
hexString = '0' + hexString; // Up to you whether to pad the first or last byte
}
byte[] data = new byte[hexString.Length / 2];
for (int i = 0; i < data.Length; i++)
{
data[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return data;
}