我一直在从 Windows azure 实现苹果推送通知。我已经能够连接到 APNS 服务器并使用证书进行身份验证。当我将流写入服务器时,我没有得到任何异常。但由于奇怪的原因,设备没有收到通知。该应用程序已注册推送通知。我不确定问题是什么。有什么方法可以检查我发送到 APNS 服务器的通知是否有效,或者即使 APNS 服务器已向应用程序发送了通知?下面是我的代码。
如果有一个经过测试和工作的代码是比这更好的实现,我也将不胜感激
APPLEHOST = "gateway.sandbox.push.apple.com";
APPLEPORT = 2195;
private void InitializeAPN()
{
applePushNotificationClient = new TcpClient(APPLEHOST, APPLEPORT);
sslStream = new SslStream(applePushNotificationClient.GetStream(), false);
try
{
sslStream.AuthenticateAsClient(APPLEHOST, APPLE_CLIENT_CERT_COLLECTION, SslProtocols.Tls, false);
}
catch (AuthenticationException ex)
{
Trace.WriteLine("Could not open APN connection: " + ex.ToString());
}
Trace.WriteLine("APN connection opened successfully.");
}
public void SendAPNMessage(string message, string deviceID)
{
try
{
MemoryStream memoryStream = new MemoryStream();
BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
// construct the message
binaryWriter.Write((byte)0);
binaryWriter.Write((byte)0);
binaryWriter.Write((byte)32);
// convert to hex and write
byte[] deviceToken = new byte[deviceID.Length / 2];
for (int i = 0; i < deviceToken.Length; i++)
{
deviceToken[i] = byte.Parse(deviceID.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
}
binaryWriter.Write(deviceToken);
// construct payload within JSON message framework
var json = new JArray(new JObject(new JProperty("aps", new JObject(new JProperty("alert", message), new JProperty("badge", 1))))).ToString();
byte[] payloadBytes = System.Text.Encoding.UTF8.GetBytes(json);
// write payload data
binaryWriter.Write((byte)0);
binaryWriter.Write((byte)payloadBytes.Length);
binaryWriter.Write(payloadBytes);
binaryWriter.Flush();
// send across the wire
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
}
catch (Exception ex)
{
Trace.WriteLine(ex.ToString());
}
Trace.WriteLine("Message successfully sent.");
}