goapns

package module
v0.0.0-...-4157da4 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2016 License: MIT Imports: 12 Imported by: 4

README

Go-APNS

Interface for Apples Push Notification System written in Go using their HTTP2 API ☄️

Installation

After setting up Go and the GOPATH variable, you download and install the dependencies by executing the following commands:

go get -u golang.org/x/net/http2
go get -u golang.org/x/crypto/pkcs12

And then install Go-APNS using this line

go get -u https://github.com/Tantalum73/Go-APNS

iOS 10 ready

New keys have been added to provide richer notifications on Apples new iOS. Those are:

  • Subtitle(string) a short string displayed below the notification that describes its purpose
  • CollapseID(string) can be used to replace a former sent notification
  • 'MutableContent()' a flag that specifies if the app is allowed to mutate the notification before it gets presented

Usage

First step: Create a Connection.

conn, err := goapns.NewConnection("<File path to your certificate in p12 format>", "<password of your certificate>")
if err != nil {
  //Do something more responsible in production
  log.Fatal(err)
}

Keep the Connection around as long as you can. Or as Apple puts it: 'You should leave a connection open unless you know it will be idle for an extended period of time--for example, if you only send notifications to your users once a day it is ok to use a new connection each day.'

Optionally, you can specify a development or production environment by calling conn.Development(). Development is the default environment. Now you are ready for the next step.


Second step: Build your notification.

According to Apples documentation, a notification consists of a header and a payload. The latter contains meta-information and the actual alert. In Go-APNS I condensed every field to a Message.

You only operate with the Message struct. It provides a method for every property that you can set.

message := goapns.NewMessage().Title("Title").Body("A Test notification :)").Sound("Default").Badge(42)
message.Custom("customKey", "customValue")
  • Create a new Message by calling goapns.NewMessage().
  • Specify values by calling a method on the message object.
  • Chain it together or call them individually.

Third Step Push your notification to a device token. Once you have you connection ready and configured the message as you like, you can send the notification to a device token. Maybe you gather the tokens in a database. You know best how to get them off there so let's just assume they are contained in an array or, like in my case, statically typed.

The magic happens when you call Push() on a Connection. The provided message is sent to Apples servers asynchronously. Therefore, you get the result delivered in a chan. When I say 'response' I mean a Response object.

tokens := []string{"<token1>",
  "<token2>"}
responseChannel := make(chan goapns.Response, len(tokens))
conn.Push(message, tokens, responseChannel)

for response := range responseChannel {
  if !response.Sent() {
    //handle the error in response.Error
  } else {
    //the notification was delivered successfully
  }
}

In case, you want to know, what JSON string exactly is pushed to Apple, you can call fmt.Println(message.JSONstring()).

Now it is up to you how to handle the error case.

For example, if the device you tried to push to has removed the app you get an Unregistered Error (response.Error == ErrorUnregistered). In this case, Apple provides the timestamp on which the device started to become unavailable. You can store this status update and the timestamp for the case that the device re-registeres itself. Then, you can compare the received timestamp and decide which token to keep and if you keep pushing to it.

Values you can set

As mentioned above, you only interact with a Messageobject. There are plenty of methods and I will list them here. You can chain those methods like this

message.Title("Title").Body("A Test notification :)").Sound("Default").Badge(42)

This method will change the Alert

  • Title(string)
  • Body(string)
  • TitleLocKey(string)
  • TitleLocArgs([] string)
  • ActionLocKey(string)
  • LocKey(string)
  • LocArgs([] string)
  • LaunchImage(string)
  • Subtitle(string) (new in iOS 10)

This method will change the Payload

  • Badge(int) if left empty, the badge will remain unchanged
  • NoBadgeChange() if you set the Badge to an int and want to unset it so it stays unchained on the app
  • Sound(string)
  • Category(string)
  • ContentAvailable() sets ContentAvailable to 1 and the priority to low, according to Apples documentation
  • ContentUnvailable() lets you reset the ContentAvailable flags you may have set earlier by accident
  • MutableContent() a flag that specifies if the app is allowed to mutate the notification before it gets presented (new in iOS 10)

This method will change the Header

  • APNSID(string) An UID you can set to identify the notification. If no ID is specified, Apples server will set one for you automatically
  • Expiration(time.Time)
  • PriorityHigh() Apple defines a value of 10 as high priority, if you do not specify the priority it will default to high
  • PriorityLow() Apple defines a value of 5 as low priority
  • Topic(string) typically the bundle ID for your app
  • CollapseID(string) can be used to replace a former sent notification (new in iOS 10)

Example

package main

import (
    "fmt"
    "log"

    "github.com/tantalum73/Go-APNS"
)

func main() {

    //creating the Connection by passing the path to a valid certificate and its passphrase
    conn, err := goapns.NewConnection("/../Push Test Push Cert.p12", "<passphrase>")
    if err != nil {
        log.Fatal(err)
    } else {
        conn.Development()
    }


    //composing the Message
    message := goapns.NewMessage().Title("Title").Body("A Test notification :)").Sound("Default").Badge(42)
    message.Custom("key", "val")


    //Tokens from a database or, in my case, statically typed
    tokens := []string{"a26f0000c052865e6631756b1b9d05b4a37ad512fabbe266dd21357b376f0e0e",
        "428dc1d681e576f69f3373d0065b1cdd8da9b76daab39203fa649c26187722c0"}

    //create a channel that gets the Response object passed in,
    //it expects as many responses as there are token to push to
    channel := make(chan goapns.Response, len(tokens))

    //Print the JSON as it is sent to Apples servers
    fmt.Println(message.JSONstring())

    //Perform the push asynchronously
    conn.Push(message, tokens, channel)

    //iterate through the responses
    for response := range channel {

        if !response.Sent() {
          //handle the error in a way that fits you
            fmt.Printf("\nThere was an error sending to device %v : %v\n", response.Token, response.Error)

                  if response.Error == goapns.ErrorUnregistered {
                      //The device was removed from APNS so the token can't be used anymore.
                      //Update you database accordingly by using the Timestamp object that
                      //gives a hint since when the token coult not be reached anymore.
                      fmt.Printf("\nToken is not registered as valid token anymore since %v\n", response.Timestamp())
                  }

        } else {
            fmt.Printf("\nPush successful for token: %v\n", response.Token)
        }

    }
}

It will send this JSON to Apples servers:

{
    "aps": {
        "alert": {
            "title": "Title",
            "body": "A Test notification :)"
        },
        "badge": 42,
        "sound": "Default"
    },
    "key": "val"
}

Apples documentation

If you want to look something up, I also recommend Apples documentation of the APNS topic:

I wrote some words about this project in my blog. Any feedback is much appreciated. I am @Klaarname on Twitter and would love to hear from you :)

If you are not happy with my solution, maybe one of those fits you better:

Go-APNS is published under MIT License.

Copyright (c) 2016 Andreas Neusuess (@Klaarname)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

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

Apple HTTP/2 Development & Production urls

View Source
const PriorityHigh = 10

PriorityHigh sepcifies a high priority for the notification. Default priotity is PriorityHigh so if you don't specify any priority, PriorityHigh is assumed.

It sends 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

View Source
const PriorityLow = 5

PriorityLow sepcifies a low priority for the notification. Default priotity is PriorityHigh so if you don't specify any priority, PriorityHigh is assumed.

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.

Variables

View Source
var (
	//ErrorCertificateExpired is an error that reports that the certificate is expired.
	ErrorCertificateExpired = errors.New("Your certificate has expired. Please renew in Apples Developer Center")
	//ErrorCertificatePrivateKeyNotRSA is an error that reports that the certificate is in the wrong format.
	ErrorCertificatePrivateKeyNotRSA = errors.New("Apparently the private key is not in RSA format, aborting.")
)
View Source
var (
	ErrorPayloadEmpty              = errors.New("The message payload was empty, expected HTTP/2 status code is 400.")
	ErrorPayloadTooLarge           = errors.New("The message payload was too large. The maximum payload size is 4096 bytes.")
	ErrorBadTopic                  = errors.New("The apns-topic was invalid.")
	ErrorTopicDisallowed           = errors.New("Pushing to this topic is not allowed.")
	ErrorBadMessageID              = errors.New("The APNSID value is bad.")
	ErrorBadExpirationDate         = errors.New("The expiration value is bad.")
	ErrorBadPriority               = errors.New("The apns-priority value is bad.")
	ErrorMissingDeviceToken        = errors.New("The device token is not specified in the request. Verify that the message is sent to a device token.")
	ErrorBadDeviceToken            = errors.New("The specified device token was bad. Verify that the request contains a valid token and that the token matches the environment.")
	ErrorDeviceTokenNotForTopic    = errors.New("The device token does not match the specified topic.")
	ErrorUnregistered              = errors.New("The device token is inactive for the specified topic. Expected HTTP/2 status code is 410.")
	ErrorDuplicateHeaders          = errors.New("One or more headers were repeated.")
	ErrorBadCertificateEnvironment = errors.New("The client certificate was for the wrong environment.")
	ErrorBadCertificate            = errors.New("The certificate was bad.")
	ErrorForbidden                 = errors.New("The specified action is not allowed.")
	ErrorBadPath                   = errors.New("The request contained a bad :path value.")
	ErrorMethodNotAllowed          = errors.New("The specified :method was not POST.")
	ErrorTooManyRequests           = errors.New("Too many requests were made consecutively to the same device token.")
	ErrorIdleTimeout               = errors.New("Idle time out.")
	ErrorShutdown                  = errors.New("The server is shutting down.")
	ErrorInternalServerError       = errors.New("An internal server error occurred.")
	ErrorServiceUnavailable        = errors.New("The service is unavailable.")
	ErrorMissingTopic              = errors.New("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.")

	ErrorBadRequest = errors.New("Bad request.")
	ErrorUnknown    = errors.New("Unknown error.")
)

Service error responses.

Functions

func CertificateFromP12

func CertificateFromP12(filePath string, key string) (tls.Certificate, error)

CertificateFromP12 loads a p12 certificate file from a given path. If can be secured by a password. You should pass it as an argument to enable Go-APNS to open it

Types

type Alert

type Alert struct {
	//Title is a short string describing the purpose of the notification.
	// Apple Watch displays this string as part of the notification interface.
	// This string is displayed only briefly and should be crafted so that it can be understood quickly.
	// This key was added in iOS 8.2.
	Title string `json:"title,omitempty"`

	//Subtitle is a short purpose of the notification.
	Subtitle string `json:"subtitle,omitempty"`

	// TitleLocKey is the key to a title string in the Localizable.strings file for the current localization.
	// The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the title-loc-args array.
	// See Localized Formatted Strings for more information.
	// This key was added in iOS 8.2.
	TitleLocKey string `json:"title-loc-key,omitempty"`

	//TitleLocArgs are variable string values to appear in place of the format specifiers in title-loc-key.
	//See Localized Formatted Strings for more information.
	//This key was added in iOS 8.2
	TitleLocArgs []string `json:"title-loc-args,omitempty"`

	//Body is the text of the alert message.
	Body string `json:"body,omitempty"`

	//LocKey is a key to an alert-message string in a Localizable.strings file for the current localization (which is set by the user’s language preference).
	// The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the loc-args array.
	// See Localized Formatted Strings for more information.
	LocKey string `json:"loc-key,omitempty"`

	//LocArgs are variable string values to appear in place of the format specifiers in loc-key.
	//See Localized Formatted Strings for more information.
	LocArgs []string `json:"loc-args,omitempty"`

	//ActionLocKey: If a string is specified, the system displays an alert that includes the Close and View buttons.
	//The string is used as a key to get a localized string in the current localization to use for the right button’s title instead of “View”.
	//See Localized Formatted Strings for more information.
	ActionLocKey string `json:"action-loc-key,omitempty"`

	//LaunchImage is the filename of an image file in the app bundle, with or without the filename extension.
	// The image is used as the launch image when users tap the action button or move the action slider.
	// If this property is not specified, the system either uses the previous snapshot,uses the image identified by the UILaunchImageFile key in the app’s Info.plist file, or falls back to Default.png.
	// This property was added in iOS 4.0.
	LaunchImage string `json:"launch-image,omitempty"`
}

Alert stores properties that belong to the Alert as specified by Apple: If this property is included, the system displays a standard alert or a banner, based on the user’s setting. You can specify a string or a dictionary as the value of alert. If you specify a string, it becomes the message text of an alert with two buttons: Close and View. If the user taps View, the app launches. If you specify a dictionary, refer to Table 5-2 for descriptions of the keys of this dictionary.

func NewAlert

func NewAlert() Alert

NewAlert creates a new Alert with empty values.

type Connection

type Connection struct {
	//HTTPClient the HTTP client that is used. It is configured with a tls.Config that uses
	//the specified certificate. It is constructed for you in NewConnection(pathname, key)
	HTTPClient http.Client
	//Certificate is the certificate that you specified during construction of the Connection
	//by using NewConnection(pathname string, key string)
	Certificate tls.Certificate
	//Host is the host to which the request is sent to.
	Host string
}

Connection stores properties that are necessary to perform a request to Apples servers.

func NewConnection

func NewConnection(pathname string, key string) (*Connection, error)

NewConnection creates a new Connection object. A Certificate is required to send requests to Apples servers. You can specify the path to a .p12 certificate and its passphrase. The default host is the development host. connection.Production() if you want to use the production environment. It will return a *Connection or an error. One of this is always nil.

func (*Connection) Development

func (c *Connection) Development() *Connection

Development sets the host to Apples development environment. Use this while your app is in development and not published. This host is set by default.

func (*Connection) Production

func (c *Connection) Production() *Connection

Production sets the host to Apples development environment. Use this while your app is in production.

func (*Connection) Push

func (c *Connection) Push(message *Message, tokens []string, responseChannel chan Response)

Push sends a request to Apples servers. It takes a Message and and tokens in an array to which the message should be pushed to. The result of a request is pushed into the responseChannel as an Response object. As the network operation is performed asynchronously (using go keyword) the method will return immediately. Use responseChannel to watch the results. You will get one Response object for every request that is sent (one request per token).

type Header struct {

	//APNSID is a canonical UUID that identifies the notification.
	//If there is an error sending the notification, APNs uses this value to identify the notification to your server.
	//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 omit this header, a new UUID is created by APNs and returned in the response.
	APNSID string

	//Expiration is a UNIX epoch date expressed in seconds (UTC).
	//This header identifies the date when the notification is no longer valid and can be discarded.
	//If this value is nonzero, APNs stores the notification and tries to deliver it at least once,
	//repeating the attempt as needed if it is unable to deliver the notification the first time.
	//If the value is 0, APNs treats the notification as if it expires immediately and does not store the notification or attempt to redeliver it.
	Expiration time.Time

	//Priority is the priority of the notification.
	//Set it to PriorityHigh or PriorityLow but do not
	//use custom numbers in any case.
	Priority int

	//Topic of the remote notification, which is typically the bundle ID for your app.
	//The certificate you create in 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

	//CollapseID specifies a string that is used to replace a former sent notification by the latest one.
	//Notifications with the same CollapseID string will be collapsed so that only the newest notification is displayed.
	//Usefull if you want to present a  scrore of a fotball math or something that gets frequently updated.
	CollapseID string
}

Header collects the header fields for the notification.

func NewHeader

func NewHeader() Header

NewHeader creates a new Header with high priority.

type Message

type Message struct {

	//Payload defines properties as they are described in Apples documentation.
	Payload Payload

	//Alert stores properties that belong to the Alert as specified by Apple.
	Alert Alert

	//Header collects the header fields for the notification.
	Header Header
	// contains filtered or unexported fields
}

Message collects Header, Payload and Alert and also provides methods to configure them.

func NewMessage

func NewMessage() *Message

NewMessage creates a new Message with default Alert, Payload and Header objects.

func (*Message) APNSID

func (m *Message) APNSID(id string) *Message

APNSID is a canonical UUID that identifies the notification. This method sets the value to its underlaying Header object. If there is an error sending the notification, APNs uses this value to identify the notification to your server. 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 omit this header, a new UUID is created by APNs and returned in the response.

func (*Message) ActionLocKey

func (m *Message) ActionLocKey(key string) *Message

ActionLocKey : If a string is specified, the system displays an alert that includes the Close and View buttons. This method sets the value to its underlaying Alert object. The string is used as a key to get a localized string in the current localization to use for the right button’s title instead of “View”. See Localized Formatted Strings for more information.

func (*Message) Badge

func (m *Message) Badge(number int) *Message

Badge is the number to display as the badge of the app icon. This method sets the value to its underlaying Payload object. If this property is absent, the badge is not changed. To remove the badge, set the value of this property to 0.

func (*Message) Body

func (m *Message) Body(body string) *Message

Body sets the text of the alert message in the underlaying Alert object.

func (*Message) Category

func (m *Message) Category(category string) *Message

Category : provide this key with a string value that represents the identifier property of the UIMutableUserNotificationCategory object you created to define custom actions. This method sets the value to its underlaying Payload object. To learn more about using custom actions, see Registering Your Actionable Notification Types.

func (*Message) CollapseID

func (m *Message) CollapseID(collapseID string) *Message

CollapseID specifies a string that is used to replace a former sent notification by the latest one. Notifications with the same CollapseID string will be collapsed so that only the newest notification is displayed. Usefull if you want to present a scrore of a fotball math or something that gets frequently updated.

func (*Message) ContentAvailable

func (m *Message) ContentAvailable() *Message

ContentAvailable : if this key is provided with a value of 1 to indicate that new content is available. This method sets the value to its underlaying Payload object. Including this key and value means that when your app is launched in the background or resumed, This method sets ContentAvailable to 1 and the priority to Low according to Apples documentation.

func (*Message) ContentUnavailable

func (m *Message) ContentUnavailable() *Message

ContentUnavailable lets you set the ContentAvailable flag to 0 and the priority to High. This method sets the value to its underlaying Payload object. Use this method if you set ContentAvailable() by accident.

func (*Message) Custom

func (m *Message) Custom(key string, object interface{}) *Message

Custom lets you set a custom key and value. It will be appended to the Notification. In your AppDelegate, you can extract those custom values.

func (*Message) Expiration

func (m *Message) Expiration(time time.Time) *Message

Expiration is a UNIX epoch date expressed in seconds (UTC). This method sets the value to its underlaying Header object. This header identifies the date when the notification is no longer valid and can be discarded. If this value is nonzero, APNs stores the notification and tries to deliver it at least once, repeating the attempt as needed if it is unable to deliver the notification the first time. If the value is 0, APNs treats the notification as if it expires immediately and does not store the notification or attempt to redeliver it.

func (*Message) JSONstring

func (m *Message) JSONstring() string

JSONstring returns the entire Message object as JSON exactly as it will be sent to Apples servers. You can use this method to debug your code.

func (*Message) LaunchImage

func (m *Message) LaunchImage(imageName string) *Message

LaunchImage is the filename of an image file in the app bundle, with or without the filename extension. This method sets the value to its underlaying Alert object. The image is used as the launch image when users tap the action button or move the action slider. If this property is not specified, the system either uses the previous snapshot,uses the image identified by the UILaunchImageFile key in the app’s Info.plist file, or falls back to Default.png. This property was added in iOS 4.0.

func (*Message) LocArgs

func (m *Message) LocArgs(args []string) *Message

LocArgs are variable string values to appear in place of the format specifiers in loc-key. This method sets the value to its underlaying Alert object. See Localized Formatted Strings for more information.

func (*Message) LocKey

func (m *Message) LocKey(key string) *Message

LocKey is a key to an alert-message string in a Localizable.strings file for the current localization (which is set by the user’s language preference). This method sets the value to its underlaying Alert object. The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the loc-args array. See Localized Formatted Strings for more information.

func (*Message) MarshalJSON

func (m *Message) MarshalJSON() ([]byte, error)

MarshalJSON builds a []byte that stores the Message object in JSON.

func (*Message) MutableContent

func (m *Message) MutableContent() *Message

MutableContent specifies if the app is allowed to mutate the notification before it gets presented. If so, your notification extension will be woken up to do the job.

func (*Message) NoBadgeChange

func (m *Message) NoBadgeChange() *Message

NoBadgeChange is a method that resets the badge. This method sets the value to its underlaying Payload object. If the Badge value is ommitted, it stays unchanged on the app. Use this method if you set the Badge (by accident) and want to unset it to let it unchanged.

func (*Message) PriorityHigh

func (m *Message) PriorityHigh() *Message

PriorityHigh sepcifies a high priority for the notification. This method sets the value to its underlaying Header object. Default priotity is PriorityHigh so if you don't specify any priority, PriorityHigh is assumed.

It sends 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

func (*Message) PriorityLow

func (m *Message) PriorityLow() *Message

PriorityLow sepcifies a low priority for the notification. This method sets the value to its underlaying Header object. Default priotity is PriorityHigh so if you don't specify any priority, PriorityHigh is assumed.

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.

func (*Message) Sound

func (m *Message) Sound(sound string) *Message

Sound specified tha name of a sound file in the app bundle or in the Library/Sounds folder of the app’s data container. This method sets the value to its underlaying Payload object. The sound in this file is played as an alert. If the sound file doesn’t exist or default is specified as the value, the default alert sound is played. The audio must be in one of the audio data formats that are compatible with system sounds.

func (*Message) Subtitle

func (m *Message) Subtitle(subtitle string) *Message

Subtitle sets the subtitle of the alert in its underlaying Alert object. It is a short purpose of the notification.

func (*Message) Title

func (m *Message) Title(title string) *Message

Title sets the title of the alert in its underlaying Alert object. It is a short string describing the purpose of the notification.

func (*Message) TitleLocArgs

func (m *Message) TitleLocArgs(args []string) *Message

TitleLocArgs are variable string values to appear in place of the format specifiers in title-loc-key. This method sets the value to its underlaying Alert object. See Localized Formatted Strings for more information. This key was added in iOS 8.2

func (*Message) TitleLocKey

func (m *Message) TitleLocKey(key string) *Message

TitleLocKey is the key to a title string in the Localizable.strings file for the current localization. This method sets the value to its underlaying Alert object. The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the title-loc-args array. See Localized Formatted Strings for more information. This key was added in iOS 8.2.

func (*Message) Topic

func (m *Message) Topic(topic string) *Message

Topic of the remote notification, which is typically the bundle ID for your app. This method sets the value to its underlaying Header object. The certificate you create in 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.

type Payload

type Payload struct {
	//Badge is the number to display as the badge of the app icon.
	//If this property is absent, the badge is not changed.
	//To remove the badge, set the value of this property to 0.
	Badge int

	//Sound specified tha name of a sound file in the app bundle or in the Library/Sounds folder of the app’s data container.
	//The sound in this file is played as an alert.
	//If the sound file doesn’t exist or default is specified as the value, the default alert sound is played.
	//The audio must be in one of the audio data formats that are compatible with system sounds.
	Sound string

	//ContentAvailable: if this key is provided with a value of 1 to indicate that new content is available.
	//Including this key and value means that when your app is launched in the background or resumed,
	//application:didReceiveRemoteNotification:fetchCompletionHandler: is called.
	ContentAvailable int

	// Category: provide this key with a string value that represents the identifier property of the UIMutableUserNotificationCategory object you created to define custom actions.
	// To learn more about using custom actions, see Registering Your Actionable Notification Types.
	Category string

	// MutabelContent specifies if the app is allowed to mutate the notification before it gets presented.
	//If so, your notification extension will be woken up to do the job.
	MutableContent int
}

Payload defines properties as they are described as in Apples documentation. Badge, Sound, ContentAvailable and Category are those. Think of Payload as a meta-object to your notification as it specify the behaviour but not the actual alert.

func NewPayload

func NewPayload() Payload

NewPayload provides a initializer of Payload with empty values and no badge.

func (*Payload) MapInto

func (p *Payload) MapInto(mapped map[string]interface{}) map[string]interface{}

MapInto is passed in a map on which the Payload content is appended to. It return a new map with every property and key set, ready to build a JSON from it.

type Response

type Response struct {
	//StatusCode defines the status code that Apples servers returned. (See HTTP status codes)
	StatusCode int

	//Reason is a string representation sent by Apples servers describing why the notification
	//failed in delivery.
	Reason string `json:"reason"`

	//TimestempNumber is an int64 that is populated if Apples servers identified a device token being unavailable
	//for a given amount of time. Apple documentation says:
	//If the value in the :status header is 410, the value of this key is the last time at which APNs confirmed that the device token was no longer valid for the topic.
	//Stop pushing notifications until the device registers a token with a later timestamp with your provider.
	TimestempNumber int64 `json:"timestamp,omitempty"`

	//Error is nil if everything worked out and not nil if something went wrong by pushing the notification.
	Error error

	//Token of the device to which the notification should be pushed to.
	Token string

	//Message object that failed to sent.
	Message *Message
}

Response defines properties that are useful to inform the calling script what happened with the request to Apples Servers. It defines a StatusCode, a Reason (if on is provided by Apple), a Timestamt that can be used to identify since when a device became unavailable (of type int64, if you need a time.Time object, please use Timestamt() method), an Error (nil if everything went fine), the Token of the device the notification was sent to and the Message object itself (can be used to figure out, what went wrong).

func (*Response) Sent

func (r *Response) Sent() bool

Sent return true if the notification was sent successfully (http status code == 200). Additionally, the Error of the Response will be nil.

func (*Response) Timestamp

func (r *Response) Timestamp() time.Time

Timestamp converts the int64 type from a Response into a time.Time object.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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