移动端通知

步骤:

1. 添加框架 UserNotifications

2. 注册远程通知

let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in

        // Enable or disable features based on authorization.
        if granted == true
        {
            print("Allow")
            UIApplication.shared.registerForRemoteNotifications()
        }
        else
        {
            print("Don't Allow")
        }
    }

3. 获取Token

  

   func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenString = deviceToken.hexString
        print("Get Push token: \(tokenString)")
    }
    
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        
        print("Fail to Register")
    }

extension Data {
    var hexString: String {
      return withUnsafeBytes {(bytes: UnsafePointer<UInt8>) -> String in
      let buffer = UnsafeBufferPointer(start: bytes, count: count)
            return buffer.map {String(format: "%02hhx", $0)}.reduce("", { $0 + $1 })
     }
  }

}

  

 

 

服务端发送远程通知配置:

  public static void pushMessage(string content, string deviceID)
        {
            int port = 2195;
            var hostname = "gateway.sandbox.push.apple.com";
            var certificatePath = HttpContext.Current.Server.MapPath("~/App_Data/com.jackyzhong.Jacky.p12") ;
            X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "hello123");
            X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
            TcpClient client = new TcpClient(hostname, port);
            SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

            try
            {
                sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
                MemoryStream memoryStream = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(memoryStream);
                writer.Write((byte)0);
                writer.Write((byte)0);
                writer.Write((byte)32);

                writer.Write(HexStringToByteArray(deviceID.ToUpper()));

                String payload = "{\"aps\":{\"alert\":\"" + content + "\",\"badge\":10,\"sound\":\"default\"}}";
                var payloadlength = System.Text.Encoding.UTF8.GetBytes(payload).Length;
                writer.Write((byte)0);
                //writer.Write((byte)payload.Length);
                writer.Write((byte)payloadlength);
                byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
                writer.Write(b1);
                writer.Flush();
                byte[] array = memoryStream.ToArray();
                sslStream.Write(array);
                sslStream.Flush();
                client.Close();
            }
            catch (System.Security.Authentication.AuthenticationException ex)
            {
                client.Close();
            }
            catch (Exception e)
            {
                client.Close();
            } 

        }


        private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            Console.WriteLine(certificate.Subject);
            return true;
        }

        private static byte[] HexStringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                              .Where(x => x % 2 == 0)
                              .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                              .ToArray();
        }

  

posted on 2016-10-05 22:59  Jackyzhong123  阅读(411)  评论(0)    收藏  举报

导航