1.安装SDK依赖库
<PackageReference Include="PushNotifications.Server" Version="1.3.35" />
<PackageReference Include="PushNotifications.Server.AspNetCore" Version="1.3.35" />
2.添加appsettings.json配置
"PushNotifications": {
"Apple": {
"CertContent": "-----BEGIN PRIVATE KEY-----\r\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEYIKoZIzj0DAQehRANCAARXCUm3Rzh/fbBv\r\n/8J8RGzDStTBPgBibPh2ctNWLGRP3iu+MCb\r\nkssjSKCF\r\n-----END PRIVATE KEY-----",
"KeyId": "LUFL2",
"TeamId": "V4M2",
"BundleId": "com.Apss.x",
"UseSandbox": false
}
},
3.Program.cs添加服务注册
services.AddPushNotifications((option) =>
{
option.ApnsJwtOptions = appleConfig;
});
4.添加具体实现
public class ApplePushService : IPushNotificationsBase
{
private readonly IApnsClient apnsClient;
public ApplePushService(IApnsClient apnsClient)
{
this.apnsClient = apnsClient;
}
public async Task<IEnumerable<SendResponse>> SendAsync(params (string clientId, string title, string subTitle, string messageContont)[] request)
{
var result = new List<SendResponse>();
foreach (var item in request)
{
try
{
var apnsRequest = new ApnsRequest(ApplePushType.Alert)
.AddToken(item.clientId)
.AddSound()
.AddAlert(item.title, item.subTitle, item.messageContont);
await apnsClient.SendAsync(apnsRequest);
}
catch (Exception ex)
{
result.Add(new(item.clientId, ex.Message));
}
}
return result;
}
}
5.interface接口约束
public interface IPushNotificationsBase
{
Task<IEnumerable<SendResponse>> SendAsync(params (string clientId, string title, string subTitle, string messageContont)[] request);
}