flutter
Flutter makes it easy and fast to build beautiful apps for mobile and beyond
- 181k
- Dart
- BSD-3-Clause
- 1 d ago
Apple Push Notifications (APNs) Server-Side library. A from-scratch Swift 6 rewrite of the original package. The public API (APNSClient) is a completely different, modern async/await surface
Repo PerfectlySoft/Perfect-Notifications, read from GitHub 1 min ago. PerfectlySoft has not joined Take My Repo.
PerfectlySoft/Perfect-Notifications is a public repo on GitHub by PerfectlySoft. Apple Push Notifications (APNs) Server-Side library. A from-scratch Swift 6 rewrite of the original package. The public API (APNSClient) is a completely different, modern async/await surface. It declares the Apache-2.0 license on GitHub. It is written mainly in Swift, has 117 stars and last changed on 2026-10-26. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-22.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
An Apple Push Notification service (APNs) provider client for Swift servers. It sends
notifications over the APNs HTTP/2 provider API with token-based (.p8 key, ES256 JWT)
authentication, using Foundation's URLSession. The only dependency is
apple/swift-crypto, for the JWT signature.
6.0.0 is a Swift 6 rewrite with a new async API. The 5.x code (NotificationPusher, on
Perfect-Net) is on the legacy branch; see Migrating from 5.x.
.package(url: "https://github.com/PerfectlySoft/Perfect-Notifications.git", from: "6.0.0"),
and add .product(name: "PerfectNotifications", package: "Perfect-Notifications") to your target.
swift-tools-version: 6.2, Swift 6 language mode).URLSession comes from FoundationNetworking, which uses the system libcurl.
APNs needs HTTP/2, so libcurl must be built with nghttp2. Ubuntu's libcurl4 is, and the
official swift:*-noble images have it.4.0.0..<5.0.0.iOS, tvOS and watchOS aren't supported targets: a provider runs on a server, and must not ship its signing key inside an app.
import PerfectNotifications let client = try APNSClient( keyID: "ABCDE12345", // from the .p8 file name teamID: "TEAM123456", // Apple Developer → Membership privateKeyPath: "/etc/myapp/AuthKey_ABCDE12345.p8", environment: .sandbox // .production for App Store / TestFlight builds ) let notification = try APNSNotification(items: [ .alertTitle("Order ready"), .alertBody("Your order is ready for pickup."), .sound("default"), .badge(1), .customPayload("orderID", "ORD-123"), ]) let response = try await client.send(notification, to: deviceToken, // hex string from the device topic: "com.example.App") // your bundle ID if response.isSuccess { print("sent, apns-id \(response.apnsID ?? "?")") } else if let error = response.error { switch error.knownReason { case .unregistered?, .badDeviceToken?: // Stop sending to this token. print("drop token (invalid since \(error.invalidatedAt.map { "\($0)" } ?? "?"))") default: print("rejected: \(error.reason)") } }
Create one client per signing key and keep it: URLSession keeps the HTTP/2 connection to APNs
open and multiplexes concurrent sends over it, as Apple asks. APNSClient is a Sendable
struct, so it can be shared across tasks; copies share the cached provider token.
APNSClient(keyID:teamID:pemString:) takes the key's PEM text instead of a path, for keys
loaded from a secrets store.
In the Apple Developer portal, under Certificates, IDs & Profiles → Keys, create a key with
Apple Push Notifications service (APNs) enabled and download the .p8 file (it can only be
downloaded once). The 10-character key ID is shown with the key, and the 10-character team ID is
under Membership. One key works for every app in the team, in both environments.
func send(_ notification: APNSNotification, to deviceToken: String, topic: String, pushType: APNSPushType = .alert, priority: APNSPriority? = nil, expiration: APNSExpiration? = nil, collapseID: String? = nil) async throws -> APNSResponse
apns-push-type): .alert, .background, .voip, .complication,
.fileProvider, .mdm, .location, .liveActivity, .pushToTalk. Several need a topic
suffix: com.example.App.voip, .complication, .pushkit.fileprovider,
.push-type.liveactivity, .location-query, .voip-ptt.apns-priority): .immediate (10, the default), .background (5: delivery
that respects the device's power state) and .low (1: never wakes the device). Background
pushes must use .background, which is their default.apns-expiration): .immediate (deliver once or drop), .relative(seconds)
or .absolute(epochSeconds).apns-collapse-id): 1–64 printable ASCII characters (! to ~, no
spaces); newer notifications with the same ID replace older ones on the device.sendAlert(to:topic:title:body:...) and sendBackground(to:topic:customData:) cover the
common cases.APNSNotificationItem builds the aps dictionary (.alertTitle, .alertBody,
.alertSubtitle, the -loc keys, .badge, .sound, .contentAvailable, .mutableContent,
.category, .threadId, .targetContentId, .interruptionLevel, .relevanceScore) and
custom top-level keys with .customPayload(key, value).
Custom values are APNSJSONValue, a Sendable JSON enum. Literals convert directly:
.customPayload("orderID", "ORD-123") .customPayload("amount", 49) .customPayload("flags", ["new": true, "ids": [1, 2, 3]]) .customPayload("orderID", .string(order.id)) // a variable: name the case .customPayload("legacy", try APNSJSONValue(jsonObject: someAnyDictionary))
APNSNotification(raw:) sends JSON bytes as is, once it has checked that they are a JSON object
with an aps dictionary, and APNSNotification(encodable:) encodes your own Encodable payload
(it must contain aps). The payload limit is checked before sending: 4096 bytes, or 5120 for
VoIP. badge must not be negative, relevanceScore must be 0–1, and JSON may nest at most 64
levels.
let results = try await client.send(notification, to: tokens, topic: "com.example.App") for r in results { switch r.result { case .success(let response) where response.isSuccess: break case .success(let response): print(r.deviceToken, "rejected:", response.error?.reason ?? "\(response.statusCode)") case .failure(let error): print(r.deviceToken, "not sent:", error) } }
Tokens are sent one after another. Each gets its own result: a bad token or a network error
for one token doesn't stop the rest. Problems shared by every token (topic, priority, payload
size) throw before anything is sent. Cancelling the calling task stops the batch without losing
what was sent: earlier tokens keep their results, and the token in flight and the rest get
.failure(.cancelled) (the one in flight may still have been delivered). For concurrency, call
send(_:to:topic:) from a task group; the requests share one HTTP/2 connection.
An APNs rejection is not a Swift error: it's an APNSResponse with statusCode and
error.reason ("BadDeviceToken", "Unregistered", …; error.knownReason maps it onto
APNSErrorReason). For HTTP 410, error.timestamp is when APNs last confirmed the token was
invalid, in milliseconds since the epoch, and error.invalidatedAt is the same as a Date.
apnsID and, in the sandbox, apnsUniqueID come from the response headers.
APNSClientError is thrown for everything the client catches itself: invalid input (device
token, topic, collapse ID, priority, expiration, key or team ID, payload size), .timedOut,
.responseTooLarge, .unexpectedRedirect, .network(...). Cancelling the calling task throws
CancellationError promptly.
The client signs a JWT with your key and reuses it for 50 minutes (Apple accepts one for up to
60). Apple refuses token updates more often than once every 20 minutes
(TooManyProviderTokenUpdates), so the client never mints a new token sooner than that.
After an ExpiredProviderToken rejection, it mints a new token and retries once if the old one is
at least 20 minutes old. After InvalidProviderToken it doesn't retry (a new token from the same
key won't help) but stops reusing the rejected token once 20 minutes have passed. Token age is
measured on a monotonic clock that counts sleep, so stepping the wall clock doesn't change when
tokens are replaced. Each
APNSClient created from a key has its own token, so share one client rather than creating many
for the same key.
APNSClient(..., timeout: 30) sets a whole-request deadline in seconds (default 30, fractions
allowed), covering connect, send and response. Past it, send throws APNSClientError.timedOut.
urlSession: parameterThe client sends through its own URLSession, built from the configuration of the session you
pass (protocol classes, proxies, TLS settings and timeouts carry over), with its own delegate. It
forwards authentication challenges, including server-trust evaluation for certificate pinning,
to your session's delegate. Other delegate callbacks aren't forwarded. It needs its own delegate
to refuse redirects and to cancel requests safely on Linux.
../, ?, #).
Topics must be bundle-ID syntax; collapse IDs are 1–64 printable ASCII characters; key and
team IDs must be 10 ASCII letters or digits. No header value can contain CR, LF, a space or
another control character. The JWT is built with JSONEncoder.APNSClientError.unexpectedRedirect instead of counting as a result."\(client)", String(reflecting:), dump(client) and Mirror
show the environment, key ID, team ID and timeout, but never the private key or the provider
token. APNSClientError.network carries the transport error's description, which never
includes request headers..p8 key out of source control, and readable only by the server's user.Environment.custom(host:port:) points the client at a mock APNs server for staging or tests.
The provider token is sent there, so only use a host you control.Verified on swift:6.2-noble and swift:6.4-noble, arm64 and x86_64: URLSession negotiates HTTP/2
with ALPN h2 against an HTTP/2-only server, reuses one connection, and multiplexes 20
concurrent sends over it. Three corelibs Foundation behaviours to know about:
responseTooLarge past 16 KiB, and discards anything later.
But corelibs keeps the transfer running after its task is cancelled. Against a local server
streaming an endless body, send threw within 0.14 s and memory stayed under 110 MB in 8 of
8 runs. corelibs went on reading 0.2–2.7 GB, though, before the connection closed, wasting
bandwidth and CPU. (Before 6.0.0's final transport, the same server got the process
OOM-killed at about 6 GB within roughly 10 seconds, because URLSession.data(for:) buffered
everything.) Reaching this needs a server that passes TLS verification for
api.push.apple.com (or your custom host). A SwiftNIO HTTP/2 transport that resets the
stream at the cap is planned for 6.1.The test suite is hermetic: requests go to a URLProtocol stub that records them (path,
headers, body, JWT signature checked with swift-crypto) and returns scripted responses. Nothing
contacts APNs. To test your own code, pass a URLSession whose configuration's protocolClasses
includes such a stub, or point Environment.custom(host:port:) at a local mock server.
The URLProtocol stub can't reproduce corelibs' real network timing, so the Linux deadlock, timeout, redirect and endless-body regressions are covered by scripted probes outside the package: a SwiftNIO HTTP/2-only server with adversarial behaviours (never answering, a 1 MiB header, 5,000 headers, a cross-origin 307, a trickled or endless body) and a client that runs the poison sequence, sub-second timeouts, hang bursts, and a race that cancels every one of 1,000 sends while it is being redirected. Release verification runs them on Swift 6.2 and 6.4, arm64 and x86_64, in containers with no network.
5.x registered named configurations on NotificationPusher and delivered results to callbacks.
6.0 has one APNSClient per key and async sends.
| 5.x | 6.0 |
|---|---|
NotificationPusher.addConfigurationAPNS(name:production:keyId:teamId:privateKeyPath:) |
let client = try APNSClient(keyID:teamID:privateKeyPath:environment:) with .sandbox or .production |
NotificationPusher(apnsTopic:expiration:priority:collapseId:) |
topic:, expiration:, priority:, collapseID: parameters of send |
pushAPNS(configurationName:deviceToken:notificationItems:callback:) |
try await client.send(APNSNotification(items: ...), to: token, topic: ...) |
pushAPNS(configurationName:deviceTokens:notificationItems:callback:) |
try await client.send(..., to: tokens, topic: ...) → [APNSBatchResult] |
NotificationResponse (status, body) |
APNSResponse (statusCode, apnsID, apnsUniqueID, error) |
.customPayload(String, Any) |
.customPayload(String, APNSJSONValue): literals work as before; wrap variables (.string(x)) or use APNSJSONValue(jsonObject:) |
| Perfect-Net / Perfect-Thread | URLSession and swift-crypto |
APNSNotificationItem's other cases keep their names. New: .alertSubtitle, .mutableContent,
.targetContentId, .interruptionLevel, .relevanceScore.
main (Swift 6 rewrite before 6.0.0)priority: is an APNSPriority? (.immediate, .background, .low) instead of an Int?,
and APNSPushType.defaultPriority returns an APNSPriority. A background push with any other
priority throws .invalidPriority..customPayload takes an APNSJSONValue, and APNSNotificationItem is properly Sendable
(and Equatable). A custom aps key throws .reservedPayloadKey.send returns [APNSBatchResult] (token plus Result) instead of
[APNSResponse], and no longer throws away every result when one token fails.APNSResponseError.timestamp is an Int64? of milliseconds (it was documented as seconds)..payloadTooLarge.APNSClientError has new cases (exhaustive switches need updating), and the inits take a
timeout:. APNSExpiration is Equatable, APNSNotification.payload is public.APNSNotification(raw:) throws: the bytes must be a JSON object with an aps dictionary, at
most 5120 bytes. Collapse IDs must be printable ASCII without spaces.4.0.0..<5.0.0 (was from: "3.0.0", which meant 3.x only and couldn't
resolve next to Perfect-SMTP 6).PerfectlySoft/Perfect-Notifications is a public repo on GitHub by PerfectlySoft. Apple Push Notifications (APNs) Server-Side library. A from-scratch Swift 6 rewrite of the original package. The public API (APNSClient) is a completely different, modern async/await surface.
It declares the Apache-2.0 license on GitHub.
Its maker tagged it for macOS. That is declared by the maker; Take My Repo has not tested it.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-10-26. GitHub counts 7 open issues and pull requests. Take My Repo does not judge from that whether it is maintained.
Flutter makes it easy and fast to build beautiful apps for mobile and beyond
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
f.k.a. Awesome ChatGPT Prompts. Share, discover, and collect prompts from the community. Free and open source — self-host for your organization with complete privacy.
An open-source remote desktop application designed for self-hosting, as an alternative to TeamViewer.

Ready to use Android and iOS mobile notification solution based on official Unity Mobile Notifications package
Server-side Swift: a map to Perfect's Swift 6 packages: HTTP server, databases, sessions, sign-in, email, FileMaker and more. PerfectLib is on the legacy branch.
Reference and documentation for Perfect (Server-side Swift). Perfect (支持服务器端Swift语言的软件函数库)使用文档和参考手册.

TensorFlow C API Class Wrapper in Server Side Swift.
A stand-alone Swift wrapper around the MySQL client library, enabling access to MySQL servers.
This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/PerfectlySoft/Perfect-NotificationsTake My Repo has not tested this on your machine. Requirements come from the project's own documentation.