Giter Club home page Giter Club logo

apnswift's Introduction

sswg:graduated|94x20 Build Documentation

APNSwift

A non-blocking Swift module for sending remote Apple Push Notification requests to APNS built on AsyncHttpClient.

Installation

To install APNSwift, just add the package as a dependency in your Package.swift.

dependencies: [
    .package(url: "https://github.com/swift-server-community/APNSwift.git", from: "5.0.0"),
]

Getting Started

APNSwift aims to provide semantically correct structures to sending push notifications. You first need to setup a APNSClient. To do that youll need to know your authentication method

let client = APNSClient(
    configuration: .init(
        authenticationMethod: .jwt(
            privateKey: try .init(pemRepresentation: privateKey),
            keyIdentifier: keyIdentifier,
            teamIdentifier: teamIdentifier
        ),
        environment: .development
    ),
    eventLoopGroupProvider: .createNew,
    responseDecoder: JSONDecoder(),
    requestEncoder: JSONEncoder(),
    byteBufferAllocator: .init(),
    backgroundActivityLogger: logger
)
defer {
    client.shutdown { _ in
        logger.error("Failed to shutdown APNSClient")
    }
}

Sending a simple notification

All notifications require a payload, but that payload can be empty. Payload just needs to conform to Encodable

struct Payload: Codable {}

try await client.sendAlertNotification(
    .init(
        alert: .init(
            title: .raw("Simple Alert"),
            subtitle: .raw("Subtitle"),
            body: .raw("Body"),
            launchImage: nil
        ),
        expiration: .immediately,
        priority: .immediately,
        topic: "com.app.bundle",
        payload: Payload()
    ),
    deviceToken: "device-token",
    deadline: .nanoseconds(Int64.max),
    logger: myLogger
)

Sending Live Activity Update / End

It requires sending ContentState matching with the live activity configuration to successfully update activity state. ContentState needs to conform to Encodable

        try await client.sendLiveActivityNotification(
            .init(
                  expiration: .immediately,
                  priority: .immediately,
                  appID: "com.app.bundle",
                  contentState: ContentState,
                  event: .update,
                  timestamp: Int(Date().timeIntervalSince1970)
            ),
            activityPushToken: activityPushToken,
            deadline: .distantFuture
        )
        try await client.sendLiveActivityNotification(
            .init(
                  expiration: .immediately,
                  priority: .immediately,
                  appID: "com.app.bundle",
                  contentState: ContentState,
                  event: .end,
                  timestamp: Int(Date().timeIntervalSince1970),
                  dismissalDate: .dismissImmediately // Optional to alter default behaviour
            ),
            activityPushToken: activityPushToken,
            deadline: .distantFuture
        )

Authentication

APNSwift provides two authentication methods. jwt, and TLS.

jwt is preferred and recommend by Apple These can be configured when created your APNSClientConfiguration

Notes: jwt requires an encrypted version of your .p8 file from Apple which comes in a pem format. If you're having trouble with your key being invalid please confirm it is a PEM file

 openssl pkcs8 -nocrypt -in /path/to/my/key.p8 -out ~/Downloads/key.pem

Logging

By default APNSwift has a no-op logger which will not log anything. However if you pass a logger in, you will see logs.

There are currently two kinds of loggers.

Background Activity Logger

This logger can be passed into the APNSClient and will log background things like connection pooling, auth token refreshes, etc.

Notification Send Logger

This logger can be passed into any of the send: methods and will log everything related to a single send request.

Server Example

Take a look at Program.swift

iOS Examples

For an iOS example, open the example project within this repo.

Once inside configure your App Bundle ID and assign your development team. Build and run the ExampleApp to iOS Simulator, grab your device token, and plug it in to server example above. Background the app and run Program.swift

Original pitch and discussion on API

apnswift's People

Contributors

kylebrowning avatar tanner0101 avatar 0xtim avatar franzbusch avatar lgaches avatar mackoj avatar florianreinhart avatar finestructure avatar timaellis avatar paunik avatar rodericj avatar ryu0118 avatar code28 avatar vojtarylko avatar jverkoey avatar grosch avatar itcohorts avatar ladiesman218 avatar mark-urbanthings avatar madsodgaard avatar lukascz avatar junyukuang avatar gverdouw avatar ffried avatar dimitribouniol avatar diggory avatar ve6yeq avatar dominatorvbn avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.