GithubHelp home page GithubHelp logo

ibm-bluemix-mobile-services / bms-pushnotifications-serversdk-swift Goto Github PK

View Code? Open in Web Editor NEW
2.0 5.0 10.0 188 KB

IBM Cloud Mobile Services - Server side Swift SDK for IBM Cloud Push Notifications Service

License: Apache License 2.0

Swift 97.30% Shell 2.70%

bms-pushnotifications-serversdk-swift's Introduction

IBM Cloud Mobile Services - Server side Swift SDK for IBM Cloud Push Notifications Service

Swift Platform Build Status Codacy Badge Coverage Status

The IBM Cloud Push Notifications service provides a unified push service to send real-time notifications to mobile and web applications. The Swift server-side SDK for sending push notifications through the IBM Cloud Push Notifications services.

Ensure that you go through IBM Cloud Push Notifications service documentation before you start.

Contents

Installation

Swift Package Manager

import PackageDescription
let package = Package(
    dependencies: [
        .package(url: "https://github.com/ibm-bluemix-mobile-services/bluemix-pushnotifications-swift-sdk.git", .upToNextMajor(from: "1.6.0"))
	]
)

Build on Linux

sudo apt-get update // not required on Mac
swift build -Xcc -fblocks -Xlinker -rpath -Xlinker $(pwd)/.build/debug/

Usage

Simple notification

Complete the following steps:

  1. Import the IBMPushNotifications framework.

    import IBMPushNotifications

Note: For Syndicated use the overrideServerHost param of PushNotifications before initliazong the PushNotifications . Eg: PushNotifications.overrideServerHost = "https://syndicated.region.net"

  1. Initialize with details about your IBM Cloud Push Notifications service.
  • Initialize with ApiKey

     //Initialize PushNotifications
     let myPushNotifications = PushNotifications(pushApiKey:"your-push-service-apiKey", pushAppGuid: "your-push-service-app_guid", pushRegion: PushNotifications.Region.US_SOUTH)
     
     // GET AUTH TOKEN
     myPushNotifications?.getAuthToken(completionHandler: { (hasToken, tokenString) in
     	if hasToken! {
     		// Send push notifications
     	}
     })
  • Initialize with AppSecret

     let myPushNotifications = PushNotifications(pushRegion: PushNotifications.Region.US_SOUTH, pushAppGuid: "your-push-service-guid", pushAppSecret: "your-push-service-appSecret")
  1. Create a simple push notification that will broadcast to all devices.

    let messageExample = Notification.Message(alert: "Testing IBMPushNotifications")
    let notificationExample = Notification(message: messageExample)
  2. Send the Push notification using the method:

    myPushNotifications.send(notification: notificationExample) { (data, status, error) in
      if error != nil {
        print("Failed to send push notification. Error: \(error!)")
      }
    }

Note: If you are using the APIKEY for Initialisation kindly call getAuthToken() , before sending any notification. This will add an Authorization header for the request.

To create a more selective push notification with specified settings that is only sent to certain devices either by deviceIds or userIds or by device platforms or based on tag-subscriptions, or to set GCM and APNs features - there are optional parameters that you can use in the corresponding initializers.

Send Bulk push notifications

To send the bulk push notifications of the following,

myPushNotifications.sendBulk(notification: [notificationExample,notificationExample1,notificationExample2]) { (data, status, error) in
	if error != nil {
		print("Failed to send push notification. Error: \(error!)")
	}
}

Notification options

Target

In Target, you pass the following values:

  • deviceIds - Array of device IDs.

  • userIds - Array of user IDs.

  • platforms - Array of platforms.

  • tagNames - Array of tag names.

    let targetExample = Notification.Target(deviceIds: ["device1","device2"],
             userIds: ["userId1", "userId2"],
             platforms: [TargetPlatform.Apple,TargetPlatform.Google,TargetPlatform.ChromeExtApp,
    TargetPlatform.WebChrome,TargetPlatform.webFirefox,TargetPlatform.WebSafari], tagNames: ["tag1", "tag2"])

Note: Do not use userIds, tagNames, platforms and deviceIds together.

Settings

Settings can contain any of the following types:

  • APNs

  • GCM

  • FirefoxWeb

  • ChromeWeb

  • SafariWeb

  • ChromeAppExt

    let notificationExample = Notification(message: messageExample,
       apnsSettings: nil, gcmSettings: nil, firefoxWebSettings: nil,
       chromeWebSettings: nil, safariWebSettings: nil, chromeAppExtSettings: nil)
APNs

APNs settings can have the following parameters:

  • badge - The number to display as the badge of the application icon

  • interactiveCategory - The category identifier to be used for the interactive push notifications

  • iosActionKey - The title for the Action key

  • sound - The name of the sound file in the application bundle. The sound of this file is played as an alert.

  • type - Notification type: DEFAULT, MIXED or SILENT

  • payload - Custom JSON payload that will be sent as part of the notification message

  • titleLocKey - 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 titleLocArgs array.

  • locKey - 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 locArgs array

  • launchImage - 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

  • titleLocArgs - Variable string values to appear in place of the format specifiers in title-loc-key

  • locArgs - Variable string values to appear in place of the format specifiers in locKey.

  • title - The title of Rich Push notifications (Supported only on iOS 10 and above)

  • subtitle - The subtitle of the Rich Notifications. (Supported only on iOS 10 and above)

  • attachmentUrl - The link to the iOS notifications media (video, audio, GIF, images - Supported only on iOS 10 and above) ,

    let apnsSetting = Notification.Settings.Apns(badge: 1, interactiveCategory: "Category",
         iosActionKey: "VIEW", sound: "Newtune.wav", type: ApnsType.DEFAULT,
         payload: ["key1":"value1"], titleLocKey: "TITLE1", locKey: "LOCKEY1",
         launchImage: "launchImage1.png", titleLocArgs: ["arg1","arg2"],
         locArgs: ["arg3","arg4"], title: "welcome to IBM Cloud Push service",
         subtitle: "Push Notifications", attachmentUrl: "https://IBMCloud.net/image.png")
GCM

GCM settings can have the following parameters:

  • collapseKey - This parameter identifies a group of messages.

  • delayWhileIdle - When this parameter is set to true, it indicates that the message should not be sent until the device becomes active.

  • payload - Custom JSON payload that will be sent as part of the notification message.

  • priority - A string value that indicates the priority of this notification. Allowed values are 'max', 'high', 'default', 'low' and 'min'. High/Max priority notifications along with 'sound' field may be used for Heads up notification in Android 5.0 or higher. sampleval='low'.

  • sound - The sound file (on device) that will be attempted to play when the notification arrives on the device.

  • timeToLive - This parameter specifies duration (in seconds) the message should be kept in GCM storage if the device is offline.

  • interactiveCategory - The category identifier to be used for the interactive push notifications.

  • icon - Specify the name of the icon to be displayed for the notification. Ensure that the icon is already packaged with the client application.

  • sync - Device group messaging makes it possible for every app instance in a group to reflect the latest messaging state.

  • visibility - private/public - Visibility of this notification, which affects how and when the notifications are revealed on a secure locked screen.

  • lights - Allows setting the notification LED color on receiving push notification.

  • style - Options to specify for Android expandable notifications. The types of expandable notifications are picture_notification, bigtext_notification, inbox_notification.

  • type - Notification type: DEFAULT or SILENT

  • androidTitle - The title of Push notifications

     let lights = Notification.Settings.GcmLights(ledArgb: GcmLED.Green, ledOnMs: 3, ledOffMs: 3)
     let style = Notification.Settings.GcmStyle(type: GcmStyleTypes.inbox_notification,
                   title: "inbox notification", url: "https://IBMCloud.net/image.png",
                   text: "some big text", lines: ["line 1","line 2"])
     let gcmSettings = Notification.Settings.Gcm(androidTitle:"title", collapseKey: "collapseKey1", delayWhileIdle: false,
                             payload: ["key1":"value1"], priority: GcmPriority.DEFAULT,
                             sound: "sound.wav", timeToLive: 2,
                             interactiveCategory: "category1", icon: "icon.png",
                             sync: false, visibility: GcmVisibility.Public,
                             lights: lights, style: style,type: FCMType.DEFAULT)
FirefoxWeb

FirefoxWeb settings can have the following parameters:

  • title - Specifies the title to be set for the WebPush notification.

  • iconUrl - The URL of the icon to be set for the WebPush notification.

  • payload - Custom JSON payload that will be sent as part of the notification message.

  • timeToLive - This parameter specifies the duration (in seconds) the message should be kept in GCM storage if the device is offline.

     let firefoxSetttings = Notification.Settings.FirefoxWeb(title: "IBM Cloud Push Notifications",
                                   iconUrl: "https://IBM Cloud.net/icon.png",
                                   payload: ["key1":"value1"], timeToLive: 3)
ChromeWeb

ChromeWeb settings can have the following parameters:

  • title - Specifies the title to be set for the WebPush notification.

  • iconUrl - The URL of the icon to be set for the WebPush notification.

  • payload - Custom JSON payload that will be sent as part of the notification message.

  • timeToLive - This parameter specifies the duration (in seconds) the message should be kept in GCM storage if the device is offline.

     let chromeSetttings = Notification.Settings.ChromeWeb(title: "IBM Cloud Push Notifications",
                                   iconUrl: "https://IBMCloud.net/icon.png",
                                   payload: ["key1":"value1"], timeToLive: 3)
SafariWeb

SafariWeb settings can have the following parameters:

  • title - Specifies the title to be set for the Safari Push Notifications.
  • urlArgs - The URL arguments that need to be used with this notification. This has to provided in the form of a JSON Array.
  • action - The label of the action button.
let safariSettings = Notification.Settings.SafariWeb(title: "IBM Cloud Push Notifications", urlArgs: ["https://IBMCloud.net"], action: "View")
ChromeAppExt

ChromeAppExt settings can have the following parameters:

  • collapseKey - This parameter identifies a group of messages.

  • delayWhileIdle - When this parameter is set to true, it indicates that the message should not be sent until the device becomes active.

  • title - Specifies the title to be set for the WebPush Notification.

  • iconUrl - The URL of the icon to be set for the WebPush Notification.

  • timeToLive - This parameter specifies how long (in seconds) the message should be kept in GCM storage if the device is offline.

  • payload - Custom JSON payload that will be sent as part of the notification message.

     let chromeAppExtSettings = Notification.Settings.ChromeAppExt(title: "IBM Cloud Push Notifications", iconUrl: "https://IBMCloud.net/icon.png", collapseKey: "collapseKey1", delayWhileIdle: false, payload: ["key1":"value1"], timeToLive: 4)

API documentation

Find the API documentation here - https://ibm-bluemix-mobile-services.github.io/API-docs/server-SDK/IBMPushNotifications/index.html

Samples and videos

Learning more

Connect with IBM Cloud

Twitter | YouTube | Blog | Facebook |

======================= Copyright 2020-21 IBM Corp.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

bms-pushnotifications-serversdk-swift's People

Contributors

ananthakrish avatar anthonyoliveri avatar antonaleksandrov avatar bjulbricht avatar davemorganibm avatar enriquel8 avatar kant avatar myselfneerav avatar rolivieri avatar svkrish avatar tfrank64 avatar tunniclm avatar vishalpalliyathu avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

bms-pushnotifications-serversdk-swift's Issues

This package depends on SwiftyJSON

We have a long-running project to burn SwiftyJSON with fire. It is obsolete since Codable arrived in Swift 4.

SwiftyJSON should be removed from this project so we can enjoy dancing on its grave.

won't authenticate

I don't think this library is authenticating properly. I get a 401 each time I try to send a message, even though I have used the correct appGuid and clientSecret from the service credentials. How can I test this?

"FPWSE0005E" - "Invalid value was provided. Check the 'target' parameter value."

Hi there,

I'm always getting this error message when sending a Push notification through this API on both Linux and macOS.

I saw that removing the target/platforms array resolve the problem, even if I agree this is in line with the swagger api documentation.

i.e. Wrong payload
{
"target" : {
"platforms" : ["A"],
"deviceIds" : [ ... ]
},
"settings" : {
"apns" : {
"sound" : "default",
"badge" : 1,
"type" : "DEFAULT",
"payload" : {
"messageId" : "messageId"
}
}
},
"message" : {
"alert" : "Test Push Swift Server"
}
}

i.e. Correct payload
{
"target" : {
"deviceIds" : [ ... ]
},
"settings" : {
"apns" : {
"sound" : "default",
"badge" : 1,
"type" : "DEFAULT",
"payload" : {
"messageId" : "messageId"
}
}
},
"message" : {
"alert" : "Test Push Swift Server"
}
}

Here is the swift code I'm using:

import BluemixPushNotifications

let pushNotifications: PushNotifications = PushNotifications(bluemixRegion: "ng.bluemix.net", bluemixAppGuid: ..., bluemixAppSecret: ...)

let target = Notification.Target(deviceIds: [...], userIds: nil, platforms: [TargetPlatform.Apple], tagNames: nil)
let notificationMessage = Notification.Message(alert: "Test Push Swift Server", url: nil)

let apnsSetting = Notification.Settings.Apns(badge: 1, category: nil, iosActionKey: nil, sound: "default", type: ApnsType.DEFAULT, payload: ["messageId" : "messageId"])

let notification = Notification(message: notificationMessage, target: target, apnsSettings: apnsSetting, gcmSettings: nil)

pushNotifications.send(notification: notification) { (errore) in
if errore != nil {
print("Failed to send push notification. Error: (errore)")
}
}

Btw the same code was working with previous version of this package.

Thanks,
Jacopo

PS Could you please also update the package dependencies tree to Kitura 1.3 ?

Fatal Error on Linux during getAuthToken

notifications = PushNotifications(...
notifications.getAuthToken { ...

Somewhere in the getAuthToken call, this happens:
Fatal error: value(forKey:) is not supported on this platform: file Foundation/NSDictionary.swift, line 36
This does not happen on the Mac, only on Linux (and thus when deploying to the cloud.)

Do I need to include something I'm not including?

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.