GithubHelp home page GithubHelp logo

shial4 / vaporgcm Goto Github PK

View Code? Open in Web Editor NEW
24.0 5.0 2.0 71 KB

A simple Android GCM/FCM library for Swift/Vapor

License: MIT License

Swift 100.00%
swift vapor vapor-swift push-notifications osx linux fcm-http fcm-notifications vapor-provider

vaporgcm's Introduction

VaporGCM

Language Vapor GitHub license Build Status CircleCI codecov

VaporGCM is a simple, yet elegant, Swift library that allows you to send Android/iOS Push Notifications using HTTP protocol in Linux & macOS. Created for Vapor. Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. Firebase Cloud Messaging

๐Ÿ”ง Installation

A quick guide, step by step, about how to use this library.

1- Add VaporGCM to your project

Add the following dependency to your Package.swift file:

.Package(url:"https://github.com/shial4/VaporGCM.git", majorVersion: 0, minor: 2)

And then make sure to regenerate your xcode project. You can use vapor xcode -y command, if you have the Vapor toolbox installed.

๐Ÿš€ Usage

1- Send Message

It's really easy to get started with the VaporGCM library! First you need to import the library, by adding this to the top of your Swift file:

import VaporGCM

The easiest way to setup VaporGCM is to create object for example in your main.swift file. Like this:

import Vapor
import VaporGCM

let drop = Droplet()
let gcm = VaporGCM(forDroplet: drop, serverKey: "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...")

After you have the VaporGCM instance, we can go ahead and create notification object. To do that we need to use GCMPayload

let gcmPayload = GCMPayload()

Creating object is simple but it comes with multiple properties to configure:

  1. title title Indicates notification title. This field is not visible on iOS phones and tablets.
  2. body body Indicates notification body text.
  3. icon icon Indicates notification icon. Default value is set to myicon
  4. sound sound Indicates a sound to play when the device receives the notification.
  5. tag tag Indicates whether each notification message results in a new entry on the notification center on . If not set, each request creates a new notification. If set, and a notification with the same tag is already being shown, the new notification replaces the existing one in notification center.
  6. color color Indicates color of the icon, expressed in #rrggbb format
  7. clickAction clickAction The action associated with a user click on the notification.
  8. bodyLocKey bodyLocKey Indicates the key to the body string for localization.
  9. bodyLocArgs bodyLocArgs Indicates the string value to replace format specifiers in body string for localization.
  10. titleLocKey titleLocKey Indicates the key to the title string for localization.
  11. titleLocArgs titleLocArgs Indicates the string value to replace format specifiers in title string for localization.

Despite of notification object we can add custom data to our message. To do that we will need Vapor JSON object

After we've created the notification object it's time to actually send the push message.

let data = JSON([
"score":"5x1",
"time":"15:10"
])

We can now create message bject which is required to send notification to device

let message = PushMessage(gcmPayload: gcmPayload, data: data)

Message object do not require Notification or JSON object. We can as well send empty message.

let message = try? PushMessage()

We can create message just with notification peyload

let message = try? PushMessage(gcmPayload: gcmPayload)

Or just with data payload

let message = try? PushMessage(data: data)

Now we can send the message with notification payload and data payload to just one device, using:

let message = try! PushMessage(gcmPayload: gcmPayload, data: data)
let response = try? gcm.send(message, to: "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...")

Sending message to device return Vapor Response object. Thanks to that we can interprate response by ourselfs and do futher steps.

VaporGCM allows us to send message to multiple device list at once by using:

try! gcm.send(message, to: ["","",""], responseHandler: { (token, response, error) in
    guard error == nil else {
        print("Something wrong happen")
        return
    }
    guard response?.status.statusCode == 200 else {
        print("Error from server")
        return
    }
    print("Device token: \(token)")
})

Sending message to multiple device return response by responseHandler for each device received and identyfied by token.

Done! To summarize

import Vapor
import VaporGCM

let drop = Droplet()
let gcm = VaporGCM(forDroplet: drop, serverKey: "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...")

let gcmPayload = GCMPayload()
let data = JSON([
    "score":"5x1",
    "time":"15:10"
])

let message = try! PushMessage(gcmPayload: gcmPayload, data: data)
let response = try? gcm.send(message, to: "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...")
try! gcm.send(message, to: ["","",""], responseHandler: { (token, response, error) in
    guard error == nil else {
        print("Something wrong happen")
        return
    }
    guard response?.status.statusCode == 200 else {
        print("Error from server")
        return
    }
    print("Device token: \(token)")
})

2- Device Group

Before sending messages to a device group, you must:

  • Obtain registration tokens for each device you want to add to the group.
  • Create the notification_key, which identifies the device group by mapping a particular group (typically a user) to all of the group's associated registration tokens.

Basic management of device groups โ€” creating and removing groups, and adding or removing devices โ€” is performed via the:

let group = DeviceGroup(operation: .create,
                            name: "appUser-Chris",
                            registrationIds: ["4", "8", "15", "16", "23", "42"])

Where DeviceGroupOperation can be:

case create
case add
case remove

Sending Device Group Message. This message will add devices with ids to exsisting group with name appUser-Chris A successful request returns a notificationKey. Save the notificationKey and the corresponding name to use in subsequent operations.

let group = DeviceGroup(operation: .add,
                                name: "appUser-Chris",
                                registrationIds: ["16", "9"])
        let response = try? gcm.sendDeviceGroup(group, forProject: "SENDER_ID")
        if let json = response?.json, response?.status.statusCode == 200 {
            let notificationKey: String = try! json.extract("notification_key")
            print(notificationKey)
        }

A successful request returns a notification_key inside JSON Save the notification_key and the corresponding name to use in subsequent operations.

โญ Contributing

Be welcome to contribute to this project! :)

โ“ Questions

You can join the Vapor slack. Or you can create an issue on GitHub.

โญ License

This project was released under the MIT license.

vaporgcm's People

Contributors

mludi avatar shial4 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

Forkers

mludi steffsan

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.