OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Discussions

Flutter SDK Setup

For Developers

Required for Setup

  • A OneSignal Account if you do not already have one
  • Your OneSignal App ID, available in Keys & IDs
  • iOS - You MUST have a Mac with a new version of Xcode.

Generate Credentials

Before setting up the Flutter SDK, you must generate the appropriate credentials for the platform(s) you are releasing on:

iOS - Generate an iOS Push Certificate

Android - Generate a Google Server API Key

Running Example project

For your convenience, we've created an example project. You can run this project for iOS and Android.

  • git clone https://github.com/OneSignal/OneSignal-Flutter-SDK.git
  • cd OneSignal-Flutter-SDK/example
  • flutter run //will list available devices, copy the device ID
  • flutter run -d {your device ID}

1. Installation

1.1 To add the OneSignal Flutter SDK to your project, edit your project's pubspec.yaml file:

dependencies:
	onesignal_flutter: ^2.0.0

1.2 Run flutter packages get to install the SDK.

1.3 Now, in your Dart code, you can use:

import 'package:onesignal_flutter/onesignal_flutter.dart'

2. Adding the Notification Service Extension (iOS)

In order to receive rich push notifications (images, buttons, videos, etc) and to enable back increment/decrement logic in your app in iOS, you need to add the Notification Service Extension.

2.1 Open the Xcode project.

2.2 Select File > New > Target

2.3 Select Notification Service Extension and press Next

2.4 Enter the product name as OneSignalNotificationServiceExtension and hit Next. Unless you are already using Swift in your project, we recommend that you use Objective-C as the language,

2.5 Press Cancel on the Activate Scheme prompt

By cancelling, you are keeping Xcode set to debug your app instead of the extension. If you selected Activate by accident, you can simply switch back to debug your app in Xcode (next to the Play button).

2.6 Open the Xcode project settings and select the OneSignalNotificationServiceExtension target. Unless you have a specific reason not to, you should set the Deployment Target to be iOS 10.

2.7 Close the Xcode project. In the /ios directory of your project, open the Podfile and add the following to the bottom (just above any post_install logic):

target 'OneSignalNotificationServiceExtension' do
  pod 'OneSignal', '>= 2.9.3', '< 3.0'
end

2.8 Open terminal, cd to the /ios directory, and run pod install.

2.9 Reopen the Xcode project. In your project, in the OneSignalNotificationServiceExtension/ folder, open NotificationService.m and replace the whole file contents with:

#import <OneSignal/OneSignal.h>

#import "NotificationService.h"

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNNotificationRequest *receivedRequest;
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.receivedRequest = request;
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    [OneSignal didReceiveNotificationExtensionRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];
    
    // DEBUGGING: Uncomment the 2 lines below and comment out the one above to ensure this extension is excuting
    //            Note, this extension only runs when mutable-content is set
    //            Setting an attachment or action buttons automatically adds this
    // NSLog(@"Running NotificationServiceExtension");
    // self.bestAttemptContent.body = [@"[Modified] " stringByAppendingString:self.bestAttemptContent.body];
    
    self.contentHandler(self.bestAttemptContent);
}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    
    [OneSignal serviceExtensionTimeWillExpireRequest:self.receivedRequest withMutableNotificationContent:self.bestAttemptContent];
    
    self.contentHandler(self.bestAttemptContent);
}

@end
import UserNotifications

import OneSignal

class NotificationService: UNNotificationServiceExtension {
    
    var contentHandler: ((UNNotificationContent) -> Void)?
    var receivedRequest: UNNotificationRequest!
    var bestAttemptContent: UNMutableNotificationContent?
    
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.receivedRequest = request;
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }
    
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            OneSignal.serviceExtensionTimeWillExpireRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
        }
    }
}

2.10 Finally, you will need to enable an App Group to share data between the Extension Service and your main app. To do so, please follow this guide

3. Add Required Capabilities (iOS)

3.1 Select your project settings and under Capabilities, enable Push Notifications
3.2 Next, enable Background Modes and check Push Notifications

4. Add the OneSignal Gradle Plugin (Android)

Add the following to the very top (Line:1 ) of your android/app/build.gradle

buildscript {
    repositories {
        // ...
        maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
    }
    dependencies {
        // ...
        // OneSignal-Gradle-Plugin
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.1, 0.99.99]'
    }
}

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'

5. Add Required Code

5.1 You can now initialize OneSignal using the following code:

OneSignal.shared.init("your_onesignal_app_id_here", {
  OSiOSSettings.autoPrompt: false,
  OSiOSSettings.inAppLaunchUrl: true
});
OneSignal.shared.setInFocusDisplayType(OSNotificationDisplayType.notification);

5.2 You can also add observers for various events, such as a new notification being received or opened, or observe changes to the subscription status:

OneSignal.shared.setNotificationReceivedHandler((OSNotification notification) {
	// will be called whenever a notification is received
});

OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
  // will be called whenever a notification is opened/button pressed.
});

OneSignal.shared.setPermissionObserver((OSPermissionStateChanges changes) {
	// will be called whenever the permission changes
	// (ie. user taps Allow on the permission prompt in iOS)
});

OneSignal.shared.setSubscriptionObserver((OSSubscriptionStateChanges changes) {
	// will be called whenever the subscription changes 
	//(ie. user gets registered with OneSignal and gets a user ID)
});

OneSignal.shared.setEmailSubscriptionObserver((OSEmailSubscriptionStateChanges emailChanges) {
	// will be called whenever then user's email subscription changes
	// (ie. OneSignal.setEmail(email) is called and the user gets registered
});

// For each of the above functions, you can also pass in a 
// reference to a function as well:

void _handleNotificationReceived(OSNotification notification) {
  
}

void main() {
  OneSignal.shared.setNotificationReceivedHandler(_handleNotificationReceived);
}

5.3 If you set autoPrompt to false in iOS settings, you can manually decide when to prompt the user for permission by calling promptUserForPushNotificationPermission:

OneSignal.shared.promptUserForPushNotificationPermission();

// If you want to know if the user allowed/denied permission,
// the function returns a Future<bool>:
bool allowed = await OneSignal.shared.promptUserForPushNotificationPermission();

If you want your app to show Settings if the user has already denied push notification permissions, you can call promptUserForPushNotificationPermission with an optional fallbackToSettings parameter set to true:

OneSignal.shared.promptUserForPushNotificationPermission(fallbackToSettings: true);

Done!

[ANDROID] - Set up the NotificationExtenderService if you want to do one of the following:

  • Receive data in the background with or without displaying a notification.
  • Override specific notification settings depending on client side app logic such as custom accent color, vibration pattern, or other any other NotificationCompat options available.

Flutter SDK Setup


For Developers

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.