apns

package
v0.11.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2023 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HostDevelopment = "https://api.sandbox.push.apple.com"
	HostProduction  = "https://api.push.apple.com"
)

Apple HTTP/2 Development & Production urls

View Source
const (
	// PriorityLow will tell APNs to send the push message at a time that takes
	// into account power considerations for the device. Notifications with this
	// priority might be grouped and delivered in bursts. They are throttled,
	// and in some cases are not delivered.
	PriorityLow = 5

	// PriorityHigh will tell APNs to send the push message immediately.
	// Notifications with this priority must trigger an alert, sound, or badge
	// on the target device. It is an error to use this priority for a push
	// notification that contains only the content-available key.
	PriorityHigh = 10
)
View Source
const (
	// 400 The collapse identifier exceeds the maximum allowed size
	ReasonBadCollapseID = "BadCollapseId"

	// 400 The specified device token was bad. Verify that the request contains a
	// valid token and that the token matches the environment.
	ReasonBadDeviceToken = "BadDeviceToken"

	// 400 The apns-expiration value is bad.
	ReasonBadExpirationDate = "BadExpirationDate"

	// 400 The apns-id value is bad.
	ReasonBadMessageID = "BadMessageId"

	// 400 The apns-priority value is bad.
	ReasonBadPriority = "BadPriority"

	// 400 The apns-topic was invalid.
	ReasonBadTopic = "BadTopic"

	// 400 The device token does not match the specified topic.
	ReasonDeviceTokenNotForTopic = "DeviceTokenNotForTopic"

	// 400 One or more headers were repeated.
	ReasonDuplicateHeaders = "DuplicateHeaders"

	// 400 Idle time out.
	ReasonIdleTimeout = "IdleTimeout"

	// 400 The apns-push-type value is invalid.
	ReasonInvalidPushType = "InvalidPushType"

	// 400 The device token is not specified in the request :path. Verify that the
	// :path header contains the device token.
	ReasonMissingDeviceToken = "MissingDeviceToken"

	// 400 The apns-topic header of the request was not specified and was
	// required. The apns-topic header is mandatory when the client is connected
	// using a certificate that supports multiple topics.
	ReasonMissingTopic = "MissingTopic"

	// 400 The message payload was empty.
	ReasonPayloadEmpty = "PayloadEmpty"

	// 400 Pushing to this topic is not allowed.
	ReasonTopicDisallowed = "TopicDisallowed"

	// 403 The certificate was bad.
	ReasonBadCertificate = "BadCertificate"

	// 403 The client certificate was for the wrong environment.
	ReasonBadCertificateEnvironment = "BadCertificateEnvironment"

	// 403 The provider token is stale and a new token should be generated.
	ReasonExpiredProviderToken = "ExpiredProviderToken"

	// 403 The specified action is not allowed.
	ReasonForbidden = "Forbidden"

	// 403 The provider token is not valid or the token signature could not be
	// verified.
	ReasonInvalidProviderToken = "InvalidProviderToken"

	// 403 No provider certificate was used to connect to APNs and Authorization
	// header was missing or no provider token was specified.
	ReasonMissingProviderToken = "MissingProviderToken"

	// 404 The request contained a bad :path value.
	ReasonBadPath = "BadPath"

	// 405 The specified :method was not POST.
	ReasonMethodNotAllowed = "MethodNotAllowed"

	// 410 The device token is inactive for the specified topic.
	ReasonUnregistered = "Unregistered"

	// 413 The message payload was too large. See Creating the Remote Notification
	// Payload in the Apple Local and Remote Notification Programming Guide for
	// details on maximum payload size.
	ReasonPayloadTooLarge = "PayloadTooLarge"

	// 429 The provider token is being updated too often.
	ReasonTooManyProviderTokenUpdates = "TooManyProviderTokenUpdates"

	// 429 Too many requests were made consecutively to the same device token.
	ReasonTooManyRequests = "TooManyRequests"

	// 500 An internal server error occurred.
	ReasonInternalServerError = "InternalServerError"

	// 503 The service is unavailable.
	ReasonServiceUnavailable = "ServiceUnavailable"

	// 503 The server is shutting down.
	ReasonShutdown = "Shutdown"
)

The possible Reason error codes returned from APNs. From table 4 in the Handling Notification Responses from APNs article

View Source
const StatusSent = http.StatusOK

StatusSent is a 200 response.

View Source
const (
	// TokenTimeout is the period of time in seconds that a token is valid for.
	// If the timestamp for token issue is not within the last hour, APNs
	// rejects subsequent push messages. This is set to under an hour so that
	// we generate a new token before the existing one expires.
	TokenTimeout = 3000
)

Variables

View Source
var (
	// TLSDialTimeout is the maximum amount of time a dial will wait for a connect
	// to complete.
	TLSDialTimeout = 20 * time.Second
	// HTTPClientTimeout specifies a time limit for requests made by the
	// HTTPClient. The timeout includes connection time, any redirects,
	// and reading the response body.
	HTTPClientTimeout = 60 * time.Second
	// TCPKeepAlive specifies the keep-alive period for an active network
	// connection. If zero, keep-alives are not enabled.
	TCPKeepAlive = 60 * time.Second
)
View Source
var (
	ErrAuthKeyNotPem   = errors.New("token: AuthKey must be a valid .p8 PEM file")
	ErrAuthKeyNotECDSA = errors.New("token: AuthKey must be of type ecdsa.PrivateKey")
	ErrAuthKeyNil      = errors.New("token: AuthKey was nil")
)

Possible errors when parsing a .p8 file.

View Source
var DefaultHost = HostDevelopment

DefaultHost is a mutable var for testing purposes

View Source
var DialTLS = func(network, addr string, cfg *tls.Config) (net.Conn, error) {
	dialer := &net.Dialer{
		Timeout:   TLSDialTimeout,
		KeepAlive: TCPKeepAlive,
	}
	return tls.DialWithDialer(dialer, network, addr, cfg)
}

DialTLS is the default dial function for creating TLS connections for non-proxied HTTPS requests.

Functions

func AuthKeyFromBytes

func AuthKeyFromBytes(bytes []byte) (*ecdsa.PrivateKey, error)

AuthKeyFromBytes loads a .p8 certificate from an in memory byte array and returns an *ecdsa.PrivateKey.

func AuthKeyFromFile

func AuthKeyFromFile(filename string) (*ecdsa.PrivateKey, error)

AuthKeyFromFile loads a .p8 certificate from a local file and returns a *ecdsa.PrivateKey.

Types

type Client

type Client struct {
	Host        string
	Certificate tls.Certificate
	Token       *Token
	HTTPClient  *http.Client
}

Client represents a connection with the APNs

func NewClient

func NewClient(certificate tls.Certificate) *Client

NewClient returns a new Client with an underlying http.Client configured with the correct APNs HTTP/2 transport settings. It does not connect to the APNs until the first Notification is sent via the Push method.

As per the Apple APNs Provider API, you should keep a handle on this client so that you can keep your connections with APNs open across multiple notifications; don’t repeatedly open and close connections. APNs treats rapid connection and disconnection as a denial-of-service attack.

If your use case involves multiple long-lived connections, consider using the ClientManager, which manages clients for you.

func NewTokenClient

func NewTokenClient(token *Token) *Client

NewTokenClient returns a new Client with an underlying http.Client configured with the correct APNs HTTP/2 transport settings. It does not connect to the APNs until the first Notification is sent via the Push method.

As per the Apple APNs Provider API, you should keep a handle on this client so that you can keep your connections with APNs open across multiple notifications; don’t repeatedly open and close connections. APNs treats rapid connection and disconnection as a denial-of-service attack.

func (*Client) CloseIdleConnections

func (c *Client) CloseIdleConnections()

CloseIdleConnections closes any underlying connections which were previously connected from previous requests but are now sitting idle. It will not interrupt any connections currently in use.

func (*Client) Development

func (c *Client) Development() *Client

Development sets the Client to use the APNs development push endpoint.

func (*Client) Production

func (c *Client) Production() *Client

Production sets the Client to use the APNs production push endpoint.

func (*Client) Push

func (c *Client) Push(n *Notification) (*Response, error)

Push sends a Notification to the APNs gateway. If the underlying http.Client is not currently connected, this method will attempt to reconnect transparently before sending the notification. It will return a Response indicating whether the notification was accepted or rejected by the APNs gateway, or an error if something goes wrong.

Use PushWithContext if you need better cancellation and timeout control.

func (*Client) PushWithContext

func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error)

PushWithContext sends a Notification to the APNs gateway. Context carries a deadline and a cancellation signal and allows you to close long running requests when the context timeout is exceeded. Context can be nil, for backwards compatibility.

If the underlying http.Client is not currently connected, this method will attempt to reconnect transparently before sending the notification. It will return a Response indicating whether the notification was accepted or rejected by the APNs gateway, or an error if something goes wrong.

type ClientManager

type ClientManager struct {
	// MaxSize is the maximum number of clients allowed in the manager. When
	// this limit is reached, the least recently used client is evicted. Set
	// zero for no limit.
	MaxSize int

	// MaxAge is the maximum age of clients in the manager. Upon retrieval, if
	// a client has remained unused in the manager for this duration or longer,
	// it is evicted and nil is returned. Set zero to disable this
	// functionality.
	MaxAge time.Duration

	// Factory is the function which constructs clients if not found in the
	// manager.
	Factory func(certificate tls.Certificate) *Client
	// contains filtered or unexported fields
}

ClientManager is a way to manage multiple connections to the APNs.

func NewClientManager

func NewClientManager() *ClientManager

NewClientManager returns a new ClientManager for prolonged, concurrent usage of multiple APNs clients. ClientManager is flexible enough to work best for your use case. When a client is not found in the manager, Get will return the result of calling Factory, which can be a Client or nil.

Having multiple clients per certificate in the manager is not allowed.

By default, MaxSize is 64, MaxAge is 10 minutes, and Factory always returns a Client with default options.

func (*ClientManager) Add

func (m *ClientManager) Add(client *Client)

Add adds a Client to the manager. You can use this to individually configure Clients in the manager.

func (*ClientManager) Get

func (m *ClientManager) Get(certificate tls.Certificate) *Client

Get gets a Client from the manager. If a Client is not found in the manager or if a Client has remained in the manager longer than MaxAge, Get will call the ClientManager's Factory function, store the result in the manager if non-nil, and return it.

func (*ClientManager) Len

func (m *ClientManager) Len() int

Len returns the current size of the ClientManager.

type Context

type Context interface {
	context.Context
}

A Context carries a deadline, a cancellation signal, and other values across API boundaries. Context's methods may be called by multiple goroutines simultaneously.

type EInterruptionLevel

type EInterruptionLevel string
const (
	// InterruptionLevelPassive is used to indicate that notification be delivered in a passive manner.
	InterruptionLevelPassive EInterruptionLevel = "passive"

	// InterruptionLevelActive is used to indicate the importance and delivery timing of a notification.
	InterruptionLevelActive EInterruptionLevel = "active"

	// InterruptionLevelTimeSensitive is used to indicate the importance and delivery timing of a notification.
	InterruptionLevelTimeSensitive EInterruptionLevel = "time-sensitive"

	// InterruptionLevelCritical is used to indicate the importance and delivery timing of a notification.
	// This interruption level requires an approved entitlement from Apple.
	// See: https://developer.apple.com/documentation/usernotifications/unnotificationinterruptionlevel/
	InterruptionLevelCritical EInterruptionLevel = "critical"
)

type EPushType

type EPushType string

EPushType defines the value for the apns-push-type header

const (
	// PushTypeAlert is used for notifications that trigger a user interaction —
	// for example, an alert, badge, or sound. If you set this push type, the
	// topic field must use your app’s bundle ID as the topic. If the
	// notification requires immediate action from the user, set notification
	// priority to 10; otherwise use 5. The alert push type is required on
	// watchOS 6 and later. It is recommended on macOS, iOS, tvOS, and iPadOS.
	PushTypeAlert EPushType = "alert"

	// PushTypeBackground is used for notifications that deliver content in the
	// background, and don’t trigger any user interactions. If you set this push
	// type, the topic field must use your app’s bundle ID as the topic. Always
	// use priority 5. Using priority 10 is an error. The background push type
	// is required on watchOS 6 and later. It is recommended on macOS, iOS,
	// tvOS, and iPadOS.
	PushTypeBackground EPushType = "background"

	// PushTypeLocation is used for notifications that request a user’s
	// location. If you set this push type, the topic field must use your app’s
	// bundle ID with .location-query appended to the end. The location push
	// type is recommended for iOS and iPadOS. It isn’t available on macOS,
	// tvOS, and watchOS. If the location query requires an immediate response
	// from the Location Push Service Extension, set notification apns-priority
	// to 10; otherwise, use 5. The location push type supports only token-based
	// authentication.
	PushTypeLocation EPushType = "location"

	// PushTypeVOIP is used for notifications that provide information about an
	// incoming Voice-over-IP (VoIP) call. If you set this push type, the topic
	// field must use your app’s bundle ID with .voip appended to the end. If
	// you’re using certificate-based authentication, you must also register the
	// certificate for VoIP services. The voip push type is not available on
	// watchOS. It is recommended on macOS, iOS, tvOS, and iPadOS.
	PushTypeVOIP EPushType = "voip"

	// PushTypeComplication is used for notifications that contain update
	// information for a watchOS app’s complications. If you set this push type,
	// the topic field must use your app’s bundle ID with .complication appended
	// to the end. If you’re using certificate-based authentication, you must
	// also register the certificate for WatchKit services. The complication
	// push type is recommended for watchOS and iOS. It is not available on
	// macOS, tvOS, and iPadOS.
	PushTypeComplication EPushType = "complication"

	// PushTypeFileProvider is used to signal changes to a File Provider
	// extension. If you set this push type, the topic field must use your app’s
	// bundle ID with .pushkit.fileprovider appended to the end. The
	// fileprovider push type is not available on watchOS. It is recommended on
	// macOS, iOS, tvOS, and iPadOS.
	PushTypeFileProvider EPushType = "fileprovider"

	// PushTypeMDM is used for notifications that tell managed devices to
	// contact the MDM server. If you set this push type, you must use the topic
	// from the UID attribute in the subject of your MDM push certificate.
	PushTypeMDM EPushType = "mdm"
)

type Notification

type Notification struct {

	// An optional canonical UUID that identifies the notification. The
	// canonical form is 32 lowercase hexadecimal digits, displayed in five
	// groups separated by hyphens in the form 8-4-4-4-12. An example UUID is as
	// follows:
	//
	//  123e4567-e89b-12d3-a456-42665544000
	//
	// If you don't set this, a new UUID is created by APNs and returned in the
	// response.
	ApnsID string

	// A string which allows multiple notifications with the same collapse
	// identifier to be displayed to the user as a single notification. The
	// value should not exceed 64 bytes.
	CollapseID string

	// A string containing hexadecimal bytes of the device token for the target
	// device.
	DeviceToken string

	// The topic of the remote notification, which is typically the bundle ID
	// for your app. The certificate you create in the Apple Developer Member
	// Center must include the capability for this topic. If your certificate
	// includes multiple topics, you must specify a value for this header. If
	// you omit this header and your APNs certificate does not specify multiple
	// topics, the APNs server uses the certificate’s Subject as the default
	// topic.
	Topic string

	// An optional time at which the notification is no longer valid and can be
	// discarded by APNs. If this value is in the past, APNs treats the
	// notification as if it expires immediately and does not store the
	// notification or attempt to redeliver it. If this value is left as the
	// default (ie, Expiration.IsZero()) an expiration header will not added to
	// the http request.
	Expiration time.Time

	// The priority of the notification. Specify ether apns.PriorityHigh (10) or
	// apns.PriorityLow (5) If you don't set this, the APNs server will set the
	// priority to 10.
	Priority int

	// A byte array containing the JSON-encoded payload of this push notification.
	// Refer to "The Remote Notification Payload" section in the Apple Local and
	// Remote Notification Programming Guide for more info.
	Payload interface{}

	// The pushtype of the push notification. If this values is left as the
	// default an apns-push-type header with value 'alert' will be added to the
	// http request.
	PushType EPushType
}

Notification represents the the data and metadata for a APNs Remote Notification.

func (*Notification) MarshalJSON

func (n *Notification) MarshalJSON() ([]byte, error)

MarshalJSON converts the notification payload to JSON.

type Payload

type Payload struct {
	// contains filtered or unexported fields
}

Payload represents a notification which holds the content that will be marshalled as JSON.

func NewPayload

func NewPayload() *Payload

NewPayload returns a new Payload struct

func (*Payload) Alert

func (p *Payload) Alert(alert interface{}) *Payload

Alert sets the aps alert on the payload. This will display a notification alert message to the user.

{"aps":{"alert":alert}}`

func (*Payload) AlertAction

func (p *Payload) AlertAction(action string) *Payload

AlertAction sets the aps alert action on the payload. This is the label of the action button, if the user sets the notifications to appear as alerts. This label should be succinct, such as “Details” or “Read more”. If omitted, the default value is “Show”.

{"aps":{"alert":{"action":action}}}

func (*Payload) AlertActionLocKey

func (p *Payload) AlertActionLocKey(key string) *Payload

AlertActionLocKey sets the aps alert action localization key on the payload. This is the the string used as a key to get a localized string in the current localization to use for the notfication right button’s title instead of “View”. See Localized Formatted Strings in Apple documentation for more information.

{"aps":{"alert":{"action-loc-key":key}}}

func (*Payload) AlertBody

func (p *Payload) AlertBody(body string) *Payload

AlertBody sets the aps alert body on the payload. This is the text of the alert message.

{"aps":{"alert":{"body":body}}}

func (*Payload) AlertLaunchImage

func (p *Payload) AlertLaunchImage(image string) *Payload

AlertLaunchImage sets the aps launch image on the payload. This is the filename of an image file in the app bundle. The image is used as the launch image when users tap the action button or move the action slider.

{"aps":{"alert":{"launch-image":image}}}

func (*Payload) AlertLocArgs

func (p *Payload) AlertLocArgs(args []string) *Payload

AlertLocArgs sets the aps alert localization args on the payload. These are the variable string values to appear in place of the format specifiers in loc-key. See Localized Formatted Strings in Apple documentation for more information.

{"aps":{"alert":{"loc-args":args}}}

func (*Payload) AlertLocKey

func (p *Payload) AlertLocKey(key string) *Payload

AlertLocKey sets the aps alert localization key on the payload. This is the key to an alert-message string in the Localizable.strings file for the current localization. See Localized Formatted Strings in Apple documentation for more information.

{"aps":{"alert":{"loc-key":key}}}

func (*Payload) AlertSubtitle

func (p *Payload) AlertSubtitle(subtitle string) *Payload

AlertSubtitle sets the aps alert subtitle on the payload. This will display a short string describing the purpose of the notification. Apple Watch & Safari display this string as part of the notification interface.

{"aps":{"alert":{"subtitle":"subtitle"}}}

func (*Payload) AlertSummaryArg

func (p *Payload) AlertSummaryArg(key string) *Payload

AlertSummaryArg sets the aps alert summary arg key on the payload. This is the string that is used as a key to fill in an argument at the bottom of a notification to provide more context, such as a name associated with the sender of the notification.

{"aps":{"alert":{"summary-arg":key}}}

func (*Payload) AlertSummaryArgCount

func (p *Payload) AlertSummaryArgCount(key int) *Payload

AlertSummaryArgCount sets the aps alert summary arg count key on the payload. This integer sets a custom "weight" on the notification, effectively allowing a notification to be viewed internally as two. For example if a notification encompasses 3 messages, you can set it to 3.

{"aps":{"alert":{"summary-arg-count":key}}}

func (*Payload) AlertTitle

func (p *Payload) AlertTitle(title string) *Payload

AlertTitle sets the aps alert title on the payload. This will display a short string describing the purpose of the notification. Apple Watch & Safari display this string as part of the notification interface.

{"aps":{"alert":{"title":title}}}

func (*Payload) AlertTitleLocArgs

func (p *Payload) AlertTitleLocArgs(args []string) *Payload

AlertTitleLocArgs sets the aps alert title localization args on the payload. These are the variable string values to appear in place of the format specifiers in title-loc-key. See Localized Formatted Strings in Apple documentation for more information.

{"aps":{"alert":{"title-loc-args":args}}}

func (*Payload) AlertTitleLocKey

func (p *Payload) AlertTitleLocKey(key string) *Payload

AlertTitleLocKey sets the aps alert title localization key on the payload. This is the key to a title string in the Localizable.strings file for the current localization. See Localized Formatted Strings in Apple documentation for more information.

{"aps":{"alert":{"title-loc-key":key}}}

func (*Payload) Badge

func (p *Payload) Badge(b int) *Payload

Badge sets the aps badge on the payload. This will display a numeric badge on the app icon.

{"aps":{"badge":b}}

func (*Payload) Category

func (p *Payload) Category(category string) *Payload

Category sets the aps category on the payload. This is a string value that represents the identifier property of the UIMutableUserNotificationCategory object you created to define custom actions.

{"aps":{"category":category}}

func (*Payload) ContentAvailable

func (p *Payload) ContentAvailable() *Payload

ContentAvailable sets the aps content-available on the payload to 1. This will indicate to the app that there is new content available to download and launch the app in the background.

{"aps":{"content-available":1}}

func (*Payload) Custom

func (p *Payload) Custom(key string, val interface{}) *Payload

Custom sets a custom key and value on the payload. This will add custom key/value data to the notification payload at root level.

{"aps":{}, key:value}

func (*Payload) InterruptionLevel

func (p *Payload) InterruptionLevel(interruptionLevel EInterruptionLevel) *Payload

InterruptionLevel defines the value for the payload aps interruption-level This is to indicate the importance and delivery timing of a notification. (Using InterruptionLevelCritical requires an approved entitlement from Apple.) See: https://developer.apple.com/documentation/usernotifications/unnotificationinterruptionlevel/

{"aps":{"interruption-level":passive}}

func (*Payload) MarshalJSON

func (p *Payload) MarshalJSON() ([]byte, error)

MarshalJSON returns the JSON encoded version of the Payload

func (*Payload) Mdm

func (p *Payload) Mdm(mdm string) *Payload

Mdm sets the mdm on the payload. This is for Apple Mobile Device Management (mdm) payloads.

{"aps":{}:"mdm":mdm}

func (*Payload) MutableContent

func (p *Payload) MutableContent() *Payload

MutableContent sets the aps mutable-content on the payload to 1. This will indicate to the to the system to call your Notification Service extension to mutate or replace the notification's content.

{"aps":{"mutable-content":1}}

func (*Payload) RelevanceScore

func (p *Payload) RelevanceScore(b float32) *Payload

The relevance score, a number between 0 and 1, that the system uses to sort the notifications from your app. The highest score gets featured in the notification summary. See https://developer.apple.com/documentation/usernotifications/unnotificationcontent/3821031-relevancescore.

{"aps":{"relevance-score":0.1}}

func (*Payload) Sound

func (p *Payload) Sound(sound interface{}) *Payload

Sound sets the aps sound on the payload. This will play a sound from the app bundle, or the default sound otherwise.

{"aps":{"sound":sound}}

func (*Payload) SoundName

func (p *Payload) SoundName(name string) *Payload

SoundName sets the name value on the aps sound dictionary. This function makes the notification a critical alert, which should be pre-approved by Apple. See: https://developer.apple.com/contact/request/notifications-critical-alerts-entitlement/

{"aps":{"sound":{"critical":1,"name":name,"volume":1.0}}}

func (*Payload) SoundVolume

func (p *Payload) SoundVolume(volume float32) *Payload

SoundVolume sets the volume value on the aps sound dictionary. This function makes the notification a critical alert, which should be pre-approved by Apple. See: https://developer.apple.com/contact/request/notifications-critical-alerts-entitlement/

{"aps":{"sound":{"critical":1,"name":"default","volume":volume}}}

func (*Payload) ThreadID

func (p *Payload) ThreadID(threadID string) *Payload

ThreadID sets the aps thread id on the payload. This is for the purpose of updating the contents of a View Controller in a Notification Content app extension when a new notification arrives. If a new notification arrives whose thread-id value matches the thread-id of the notification already being displayed, the didReceiveNotification method is called.

{"aps":{"thread-id":id}}

func (*Payload) URLArgs

func (p *Payload) URLArgs(urlArgs []string) *Payload

URLArgs sets the aps category on the payload. This specifies an array of values that are paired with the placeholders inside the urlFormatString value of your website.json file. See Apple Notification Programming Guide for Websites.

{"aps":{"url-args":urlArgs}}

func (*Payload) UnsetBadge

func (p *Payload) UnsetBadge() *Payload

UnsetBadge removes the badge attribute from the payload. This will leave the badge on the app icon unchanged. If you wish to clear the app icon badge, use ZeroBadge() instead.

{"aps":{}}

func (*Payload) UnsetRelevanceScore

func (p *Payload) UnsetRelevanceScore() *Payload

Unsets the relevance score that the system uses to sort the notifications from your app. The highest score gets featured in the notification summary. See https://developer.apple.com/documentation/usernotifications/unnotificationcontent/3821031-relevancescore.

{"aps":{"relevance-score":0.1}}

func (*Payload) ZeroBadge

func (p *Payload) ZeroBadge() *Payload

ZeroBadge sets the aps badge on the payload to 0. This will clear the badge on the app icon.

{"aps":{"badge":0}}

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

func New

func New() (p *Provider)

func (*Provider) Send

func (p *Provider) Send(productionMode bool, certificate tls.Certificate, deviceToken string, topic string, payload map[string]interface{}) (err error)

Send 发送消息 mode 模式:development、production certificate 证书文件

type Response

type Response struct {

	// The HTTP status code returned by APNs.
	// A 200 value indicates that the notification was successfully sent.
	// For a list of other possible status codes, see table 6-4 in the Apple Local
	// and Remote Notification Programming Guide.
	StatusCode int

	// The APNs error string indicating the reason for the notification failure (if
	// any). The error code is specified as a string. For a list of possible
	// values, see the Reason constants above.
	// If the notification was accepted, this value will be "".
	Reason string

	// The APNs ApnsID value from the Notification. If you didn't set an ApnsID on the
	// Notification, this will be a new unique UUID which has been created by APNs.
	ApnsID string

	// If the value of StatusCode is 410, this is the last time at which APNs
	// confirmed that the device token was no longer valid for the topic.
	Timestamp Time
}

Response represents a result from the APNs gateway indicating whether a notification was accepted or rejected and (if applicable) the metadata surrounding the rejection.

func (*Response) Sent

func (c *Response) Sent() bool

Sent returns whether or not the notification was successfully sent. This is the same as checking if the StatusCode == 200.

type Time

type Time struct {
	time.Time
}

Time represents a device uninstall time

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(b []byte) error

UnmarshalJSON converts an epoch date into a Time struct.

type Token

type Token struct {
	sync.Mutex
	AuthKey  *ecdsa.PrivateKey
	KeyID    string
	TeamID   string
	IssuedAt int64
	Bearer   string
}

Token represents an Apple Provider Authentication Token (JSON Web Token).

func (*Token) Expired

func (t *Token) Expired() bool

Expired checks to see if the token has expired.

func (*Token) Generate

func (t *Token) Generate() (bool, error)

Generate creates a new token.

func (*Token) GenerateIfExpired

func (t *Token) GenerateIfExpired() (bearer string)

GenerateIfExpired checks to see if the token is about to expire and generates a new token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL