• Stars
    star
    114
  • Rank 297,177 (Top 7 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created almost 8 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Apple Push Notifications (APNs) Server-Side library.

Perfect-Notifications 简体中文

Get Involed with Perfect!

Swift 5.2 Platforms OS X | Linux License Apache

APNs remote Notifications for Perfect. This package adds push notification support to your server. Send notifications to iOS/macOS devices.

Building

This is a Swift Package manager based project. Add this repository as a dependency in your Package.swift file.

.package(url:"https://github.com/PerfectlySoft/Perfect-Notifications.git", from: "5.0.0")

Overview

This system runs on the server side. Typically at app launch, an Apple device will register with Apple's system for remote notifications. Doing so will return to the device an ID which can be used by external systems to address the device and send notifications through APNs.

When the device obtains its ID it will need to transmit it to your server. Your server will store this id and use it when sending notifications to one or more devices through APNs.

Obtain APNs Auth Key

To connect your server to Apple's push notification system you will first need to obtain an "APNs Auth Key". This key is used on your server to configure its APNs access. You can generate this key through your Apple developer account portal. Log in to your developer account and choose "Certificates, IDs & Profiles" from the menu. Then, under "Keys", choose "All".

If you haven't already created and downloaded the auth key, click "+" to create a new one. Enter a name for the key and make sure you select Apple Push Notifications service (APNs). This one key can be used for both development or production and can be used for any of your iOS/macOS apps.

Click "Continue", then "Confirm", then you will be given a chance to download the private key. You must download this key now and save the file. Also copy the "Key ID" shown in the same view. This will be a 10 character string.

Finally you will need to locate your developer team id. Click "Account" near the window's top. Select "Membership" in the menu. You will then be shown much of your personal information, including "Team ID". This is another 10 character string. Copy this value.

Server Configuration

To send notifications from your server your must have three pieces of information:

  1. The private key file which was downloaded
  2. The 10 character key id
  3. Your 10 character team id
  4. An iOS/macOS app id

These four pieces of information are used to perform push notifications. This information must reside on your server. You can store this information in any manner provided it can be used by the server. For simplicity, the rest of this example assumes that the private key file is in the server's working directory and that the two keys and the app id are embedded in the Swift code.

In your server Swift code, you must import PerfectNotifications. Then, before you start any HTTP servers or send any notifications you must add a "configuration" for the notifications you will be sending. This very simply ties your APNs keys to a name which you can then use later when pushing notifications.

import PerfectNotifications

// your app id. we use this as the configuration name, but they do not have to match
let notificationsAppId = "my.app.id"

let apnsKeyIdentifier = "AB90CD56XY"
let apnsTeamIdentifier = "YX65DC09BA"
let apnsPrivateKeyFilePath = "./APNsAuthKey_AB90CD56XY.p8"

NotificationPusher.addConfigurationAPNS(
	name: notificationsTestId, 
	production: false, // should be false when running pre-release app in debugger
	keyId: apnsKeyIdentifier, 
	teamId: apnsTeamIdentifier, 
	privateKeyPath: apnsPrivateKeyFilePath)

After the configuration has been added, notifications can be sent at any point. To do so, create a NotificationPusher with your app id, or "topic", then trigger a notification to one or more devices by calling its pushAPNS function:

let deviceIds: [String] = [...]
let n = NotificationPusher(apnsTopic: notificationsTestId)
n.pushAPNS(
	configurationName: notificationsTestId, 
	deviceTokens: deviceIds, 
	notificationItems: [.alertBody("Hello!"), .sound("default")]) {
		responses in
		print("\(responses)")
		...
}

The topic is required when creating a NotificationPusher. Additional optional parameters can be provided to customize the notification's expiration, priority and collapse-id. Consult Apple's APNS documentation for the semantics of these options.

Public API

The full public version 3.0 API for notification pusher follows:

public class NotificationPusher {
	
	/// Add an APNS configuration which can be later used to push notifications.
	public static func addConfigurationAPNS(
		name: String, 
		production: Bool, 
		keyId: String, 
		teamId: String, 
		privateKeyPath: String)

	/// Initialize given an apns-topic string.
	public init(
		apnsTopic: String,
		expiration: APNSExpiration = .immediate,
		priority: APNSPriority = .immediate,
		collapseId: String? = nil)
		
	/// Push one message to one device.
	/// Provide the previously set configuration name, device token.
	/// Provide a list of APNSNotificationItems.
	/// Provide a callback with which to receive the response.
	public func pushAPNS(
		configurationName: String, 
		deviceToken: String, 
		notificationItems: [APNSNotificationItem], 
		callback: @escaping (NotificationResponse) -> ())
	
	/// Push one message to multiple devices.
	/// Provide the previously set configuration name, and zero or more device tokens. The same message will be sent to each device.
	/// Provide a list of APNSNotificationItems.
	/// Provide a callback with which to receive the responses.
	public func pushAPNS(
		configurationName: String, deviceTokens: [String],
		notificationItems: [APNSNotificationItem],
		callback: @escaping ([NotificationResponse]) -> ())
}

The remaining structures, including APNSNotificationItem follow:

/// Items to configure an individual notification push.
public enum APNSNotificationItem {
    /// alert body child property
	case alertBody(String)
    /// alert title child property
	case alertTitle(String)
    /// alert title-loc-key
	case alertTitleLoc(String, [String]?)
    /// alert action-loc-key
	case alertActionLoc(String)
    /// alert loc-key
	case alertLoc(String, [String]?)
    /// alert launch-image
	case alertLaunchImage(String)
    /// aps badge key
	case badge(Int)
    /// aps sound key
	case sound(String)
    /// aps content-available key
	case contentAvailable
	/// aps category key
	case category(String)
	/// aps thread-id key
	case threadId(String)
    /// custom payload data
	case customPayload(String, Any)
    /// apn mutable-content key
	case mutableContent
}

public enum APNSPriority: Int {
	case immediate = 10
	case background = 5
}

/// Time in the future when the notification, if has not be able to be delivered, will expire.
public enum APNSExpiration {
	/// Discard the notification if it can't be immediately delivered.
	case immediate
	/// now + seconds
	case relative(Int)
	/// absolute UTC time since epoch
	case absolute(Int)
}

/// The response object given after a push attempt.
public struct NotificationResponse: CustomStringConvertible {
	/// The response code for the request.
	public let status: HTTPResponseStatus
	/// The response body data bytes.
	public let body: [UInt8]
	/// The body data bytes interpreted as JSON and decoded into a Dictionary.
	public var jsonObjectBody: [String:Any]
	/// The body data bytes converted to String.
	public var stringBody: String
	public var description: String
}

Additional Notes

APNs requests are made from your server to Apple's servers "api.development.push.apple.com" or "api.push.apple.com" on port 443. One request will be used when sending one notification to one or more devices. Each connection will remain open and will be reused when sending subsequent notifications. If a connection "goes away" or there are no idle connections that can be used then a new connection will be opened. This is in accordance with Apple's recommended usage of APNs and should provide the best throughput when dealing with many concurrent notification requests.

Consult Perfect-NotificationsExample for a client/server combination which can be easily configured with your own information to quickly get APNS notifications for your apps.

Further Information

For more information on the Perfect project, please visit perfect.org.

More Repositories

1

Perfect

Server-side Swift. The Perfect core toolset and framework for Swift Developers. (For mobile back-end development, website and API development, and more…)
Swift
13,834
star
2

PerfectDocs

Reference and documentation for Perfect (Server-side Swift). Perfect (支持服务器端Swift语言的软件函数库)使用文档和参考手册.
HTML
568
star
3

PerfectTemplate

Empty Perfect Starter Project.
Swift
223
star
4

Perfect-TensorFlow

TensorFlow C API Class Wrapper in Server Side Swift.
Swift
166
star
5

Perfect-MySQL

A stand-alone Swift wrapper around the MySQL client library, enabling access to MySQL servers.
Swift
124
star
6

Perfect-HTTPServer

HTTP server for Perfect.
Swift
108
star
7

Perfect-CRUD

CRUD is an object-relational mapping (ORM) system for Swift 4+.
Swift
63
star
8

Perfect-Python

An expressway to import Python 2.7 modules into Server Side Swift
Swift
61
star
9

Perfect-PostgreSQL

A stand-alone Swift wrapper around the libpq client library, enabling access to PostgreSQL servers.
Swift
54
star
10

Perfect-MongoDB

A stand-alone Swift wrapper around the mongo-c client library, enabling access to MongoDB servers.
Swift
52
star
11

Perfect-SQLite

A stand-alone Swift wrapper around the SQLite 3 client library.
Swift
49
star
12

Perfect-CURL

cURL support for Perfect.
Swift
40
star
13

Perfect-Markdown

A solution to convert markdown text into html presentation in Swift, based on GerHobbelt's "upskirt" project.
Swift
39
star
14

Perfect-Heroku-Buildpack

Swift + Perfect Buildpack for Heroku
Shell
38
star
15

Perfect-Ubuntu

Install Swift and Perfect dependencies into an Ubuntu 16.04 system.
Shell
36
star
16

Perfect-FileMaker

A stand-alone Swift wrapper around the FileMaker XML Web publishing interface, enabling access to FileMaker servers.
Swift
33
star
17

Perfect-HTTP

Base HTTP Support for Perfect.
Swift
31
star
18

Perfect-Crypto

Cryptographic Operations
Swift
28
star
19

Perfect-Redis

A Swift client for Redis.
Swift
28
star
20

Perfect-Net

Core asynchronous networking package used in Perfect. Includes support for TCP, SSL, UNIX socket files and IO event handling.
Swift
27
star
21

Perfect-LDAP

A simple Swift class wrapper of OpenLDAP.
Swift
26
star
22

Perfect-Mustache

Mustache template support for Perfect.
Swift
24
star
23

Perfect-Kafka

An Express Swift Client of Apache Kafka 0.8, the Stream Processing Platform
Swift
24
star
24

Perfect-WebSockets

WebSockets support for Perfect.
Swift
23
star
25

Perfect-SysInfo

This project provides a Swift library to monitor system performance in essential metrics.
Swift
23
star
26

Perfect-Mosquitto

A Swift Class Wrapper of Perfect-libMosquitto, the MQTT client
Swift
23
star
27

Perfect-Zip

Perfect Zip compression utility.
Swift
21
star
28

Perfect-SMTP

SMTP Client for Perfect.
Swift
21
star
29

PerfectAppTemplate

Provides a structure for a larger project to grow into. It contains an HTTP Server config that loads from pre-separated Filters and Routes, a JSON config loader, and directories into which you can organize your handlers, objects and utility functions.
Swift
21
star
30

Perfect-NIO

Perfect 4 NIO
Swift
20
star
31

Perfect-Logger

File-Based Logging.
Swift
19
star
32

Perfect-Thread

Core threading library for Perfect Server Side Swift. Includes support for serial and concurrent thread queues, locks, read/write locks and events.
Swift
18
star
33

Perfect-XML

XML support for Perfect.
Swift
16
star
34

Perfect-Authentication

OAuth2 Implementations with Facebook, Google, LinkedIn, Slack, SalesForce and GitHub providers.
Swift
15
star
35

Perfect-INIParser

A lightweight INI file parser in Server Side Swift
Swift
15
star
36

Perfect-LocalMirror

Perfect Server Local Image Builder 编译加速器
Shell
14
star
37

Perfect-COpenSSL

C module OpenSSL import for Perfect.
C
12
star
38

Perfect-OAuth2

OAuth2 Implementations with Facebook, Google, LinkedIn, Slack, SalesForce and GitHub providers.
Swift
10
star
39

Perfect-Stripe

Server Side Swift 3 Stripe API
Swift
10
star
40

Perfect-FastCGI

FastCGI server for Perfect.
Swift
9
star
41

Perfect-libxml2

libxml2 support module for Perfect.
Swift
8
star
42

Perfect-Local-Auth-PostgreSQL-Template

Template starter template for a Local Authentication - equipped server
CSS
8
star
43

PerfectAPIGenerator

Documentation generator for the Perfect API, written in Perfect.
JavaScript
8
star
44

Perfect-MariaDB

A stand-alone Swift wrapper around the MariaDB client library, enabling access to MariaDB servers. http://www.perfect.org
Swift
8
star
45

Perfect-Hadoop

Perfect Hadoop: WebHDFS, MapReduce & Yarn.
Swift
8
star
46

PerfectDocGenerator

The Perfect Documentation build process.
Swift
7
star
47

Perfect-FastCGI-Apache2.4

mod_perfect - Apache FastCGI connector
C++
7
star
48

Perfect-LocalAuthentication-PostgreSQL

Local Authentication processes and routes
Swift
6
star
49

Perfect-ZooKeeper

A ZooKeeper Client in Swift (LINUX ONLY)
Swift
6
star
50

Perfect-COpenSSL-Linux

C module OpenSSL import for Perfect (Linux).
C++
6
star
51

Perfect-WebRedirects

Filter for specified routes (including trailing wildcard routes) and perform redirects as instructed if a match is found.
Swift
5
star
52

Perfect-libcurl

C module libcurl import for Perfect.
C
5
star
53

Perfect-Turnstile-MongoDB

A MongoDB ORM single-package integration for Turnstile authentication.
Swift
5
star
54

Perfect-LinuxBridge

C module Linux compatibility import for Perfect
C
5
star
55

Perfect-Repeater

A simple library that takes a closure and executes it at the specified interval until the closure returns false or the application is terminated.
Swift
5
star
56

Perfect-Turnstile-MySQL

A MySQL ORM single-package integration for Turnstile authentication.
Swift
5
star
57

Perfect-Session-MySQL

MySQL Driver for Perfect Sessions.
Swift
4
star
58

Perfect-OpenLDAP

OpenLDAP C Library for Swift.
Swift
4
star
59

Perfect-LocalAuthentication-MySQL

Local Authentication, MySQL module
Swift
4
star
60

Perfect-Turnstile-PostgreSQL

A PostgreSQL ORM single-package integration for Turnstile authentication.
Swift
4
star
61

Perfect-libMosquitto

C library of Mosquitto (MQTT client) for Swift
Swift
4
star
62

Perfect-Session

Session drivers (for use in Perfect projects).
Swift
4
star
63

Perfect-sqlite3-support

C module import for sqlite3.
Swift
4
star
64

Perfect-Session-MongoDB

Perfect Session Drivers for MongoDB.
Swift
4
star
65

Perfect-Turnstile-SQLite

An SQLite ORM single-package integration for Turnstile authentication.
Swift
4
star
66

PerfectTemplateFCGI

Perfect Empty Starter Project for FastCGI.
Swift
3
star
67

Perfect-libSASL

SASL C library for Swift.
C
3
star
68

Perfect-CZlib-src

C
3
star
69

Perfect-SPNEGO

A general Server Side Swift library that implements SPNEGO mechanism.
C
3
star
70

Perfect-Session-Redis

Redis Driver for Perfect Sessions
Swift
3
star
71

Perfect-CouchDB

CouchDB Database Connector for Perfect.
Swift
3
star
72

Perfect-Local-Auth-MySQL-Template

CSS
3
star
73

PerfectTemplateAppEngine

Perfect Empty Starter Project for Google App Engine.
Swift
3
star
74

Perfect-Session-PostgreSQL

PostgreSQL Driver for Perfect Sessions.
Swift
3
star
75

Perfect-mysqlclient

C module import for MySQL client.
Swift
3
star
76

Perfect-GoogleAnalytics-MeasurementProtocol

Server side Google Analytics, using Swift / Perfect
Swift
2
star
77

Perfect-ODBC

Perfect connector for ODBC databases
Swift
2
star
78

Perfect-Session-SQLite

SQLite driver for Perfect Sessions.
Swift
2
star
79

Perfect-mariadbclient

C module import for MariaDB client.
Swift
2
star
80

Perfect-NewRelic-Linux

This project provides a Swift class wrapper for New Relic Agent SDK.
Swift
2
star
81

PerfectDocsUI

User interface for Perfect Docs Dev.
JavaScript
2
star
82

Archived-Perfect-Issues

JIRA Archive of Perfect.
Swift
2
star
83

Perfect-Turnstile-CouchDB

A CouchDB ORM single-package integration for Turnstile authentication.
Swift
2
star
84

Perfect-libpq

C module import for libpq.
Swift
2
star
85

Perfect-libpq-linux

C module import for libpq.
Swift
2
star
86

Perfect-mysqlclient-Linux

C module import for MySQL client Linux.
Swift
1
star
87

Perfect-Session-CouchDB

CouchDB Driver for Perfect Sessions.
Swift
1
star
88

Perfect-CloudFormation

Support for CloudFormation server instances.
Swift
1
star
89

Perfect-mongo-c-linux

Obsolete - Perfect Mongodb c-binding for linux.
Swift
1
star
90

Perfect-NIOCompat

Perfect 3 -> 4 compatability
Swift
1
star
91

Perfect-mongo-c

Obsolete - C module import for mongo-c.
Swift
1
star
92

Perfect-Assistant-Issues

Tracking issues with Perfect Assistant
1
star
93

Perfect-mariadbclient-Linux

C module import for MariaDB client Linux.
Swift
1
star