Golang: Send Push Notification to iOS device
Contents
Assumptions
- Go language is installed in your computer
- iOS sample application with APNs support for testing
Step1: Generate certificate PEM file. This article will help you to generate PEM [https://www.raywenderlich.com/123862/push-notifications-tutorial]
Step2: Install Go library for APNs
go get github.com/anachronistic/apns
Step3: Write the following function in your main.go. Place certificate PEM file in config folder. You can change push URL as per your requirement.
func SendPushToClient(pushText string,pushToken string) {
fmt.Println("SendPushToClient")
payload := apns.NewPayload()
payload.Alert = pushText
pn := apns.NewPushNotification()
pn.DeviceToken = pushToken
pn.AddPayload(payload)
client := apns.NewClient("gateway.sandbox.push.apple.com:2195", "./config/pushcert.pem", "./config/pushcert.pem")
resp := client.Send(pn)
alert, _ := pn.PayloadString()
fmt.Println("Alert:", alert)
fmt.Println("Success:", resp.Success)
fmt.Println("Error:", resp.Error)
}
Step4: Call “SendPushToClient” function from main function. Replace client token in the following code
func main() {
SendPushToClient("Hello from APN","<CLIENT TOKEN>")
}
Step5: Compile & run
go run main
Full source code main.go
package main
import (
"fmt"
"github.com/anachronistic/apns"
)
func main() {
SendPushToClient("Hello from APN","<CLIENT TOKEN>")
}
func SendPushToClient(pushText string,pushToken string) {
fmt.Println("SendPushToClient")
fmt.Println("pushText: ", pushText)
fmt.Println("pushToken: ", pushToken)
payload := apns.NewPayload()
payload.Alert = pushText
pn := apns.NewPushNotification()
pn.DeviceToken = pushToken
pn.AddPayload(payload)
client := apns.NewClient("gateway.sandbox.push.apple.com:2195", "./config/pushcert.pem", "./config/pushcert.pem")
resp := client.Send(pn)
alert, _ := pn.PayloadString()
fmt.Println("Alert:", alert)
fmt.Println("Success:", resp.Success)
fmt.Println("Error:", resp.Error)
}