飞扬的Blog
主页
登录
.Net Core 与 APNs通信给用户设备发送 UserNotifications
"date"
:
"2020-06-12 03:03:27"
"classfiy"
:
"swift"
"author"
:
"飞扬"
"viewTimes"
:
390
返回
### made 以后请面向 google 编程... ------------ 1. 在[开发者后台](https://developer.apple.com/account/resources "开发者后台")申请一个 Tpye 为 Apple Push Services 的 Certificates,申请过程中按照提示做就可以了。 2. **要注意的地方:最后一步他会让上传一个 Certificate Signing Request 文件** 这个文件在这里创建: [官方说明](https://help.apple.com/developer-account/#/devbfa00fef7 "官方说明") 3. 创建完毕后下载此证书导入到mac里,然后在mac的钥匙串里右键此证书导出一个 .p12 后缀并带有密码的文件,此文件在和APNs交互的时候必须用到。 ------------ 这里是通过APNs给用户发通知的代码: ```csharp using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using System.Collections.Generic; namespace Test.APNs { class NotificationModel { public NotificationBodyModel aps { get; set; } } class NotificationBodyModel { public UserInfo alert { get; set; } public string sound { get; set; } public int badge { get; set; } } class UserInfo { public string title { get; set; } public string subtitle { get; set; } public string body { get; set; } } class Program { static void Main(string[] args) { var model = new NotificationModel(); model.aps = new NotificationBodyModel() { sound= "default", badge = 0 }; model.aps.alert = new UserInfo() { title = "这是一个推送", //subtitle = "标题2", body = "内容", }; var datastr = JsonConvert.SerializeObject(model); var handler = new HttpClientHandler(); X509Certificate2 certificate = new X509Certificate2("/Users/fysmart/Desktop/ApplePushServices_Fysmart_tools.p12", "password"); handler.ClientCertificates.Add(certificate); var client = new HttpClient(handler); var request = new HttpRequestMessage(HttpMethod.Post, "https://api.development.push.apple.com/3/device/33c5912dbf02593a82jg62gsb53616608f3b3fb423d8c25f3467989c878c74"); request.Version = new Version(2, 0); request.Content = new StringContent(datastr); request.Headers.Add("apns-push-type", "alert"); request.Headers.Add("apns-expiration", "0"); request.Headers.Add("apns-priority", "10"); request.Headers.Add("apns-topic", "com.fysmart.*****-*****"); var response = client.SendAsync(request).GetAwaiter().GetResult(); if (response.StatusCode == HttpStatusCode.OK) { IEnumerable<string> values; response.Headers.TryGetValues("apns-id", out values); var a = values.GetEnumerator(); var id = a.MoveNext() ? a.Current : ""; Console.WriteLine("push 成功,apns-id:" + id); } else { Console.WriteLine("Response: " + response.Content.ReadAsStringAsync().GetAwaiter().GetResult()); } Console.ReadLine(); } } } ```