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

Instructions for adding the OneSignal Flutter SDK to your Flutter app for iOS and Android

Step 1 - Requirements

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

While 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 after completing Step 2 below.

Android - Generate a Google Firebase 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}

Step 2 - Add the OneSignal Flutter SDK

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

dependencies:
    onesignal_flutter: ^2.0.0

2.2 Run flutter packages get to install the SDK.

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

import 'package:onesignal_flutter/onesignal_flutter.dart'

Step 3 - Add an iOS Service Extension (iOS Apps Only)

The OneSignalNotificationServiceExtension allows your application (in iOS) to receive rich notifications with images and/or buttons, along with Badges and analytics.

3.1 Open your Xcode project.

3.2 Select File > New > Target

3.3 Select Notification Service Extension and press Next

3.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. Do not select "Activate" on the dialog shown after selecting "Finish".

3.5 Press Cancel on the Activate Scheme prompt

By canceling, 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).

3.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.

3.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
  #use_frameworks!
  pod 'OneSignal', '>= 2.9.3', '< 3.0'
end

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

If you see the error below, remove # from the above in front of use_frameworks! and try again.

- Runner (true) and OneSignalNotificationServiceExtension (false) do not both set use_frameworks!.

3.9 Open the newly created <project-name>.xcworkspace file.
Make sure to always open the workspace from now on.
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)
        }
    }
}

3.10 Finally, you will need to enable an App Group to use Confirmed Deliveries and increment/decrement Badges through push notifications.

Please follow the iOS SDK App Groups setup guide to add the OneSignal App Group in your app.

Step 4 - Enable iOS Push Capability in Xcode (iOS Apps Only)

4.1 Select your project settings and under Capabilities, enable Push Notifications
4.2 Next, enable Background Modes and check Push Notifications

Step 4 - Set up OneSignal for Android

4.1 Add the OneSignal Gradle Plugin

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.6, 0.99.99]'
    }
}

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

Step 5 - Initialize the OneSignal SDK (All Platforms)

5.1 You can now initialize OneSignal using the following code in your main.dart file:

//Remove this method to stop OneSignal Debugging 
OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);

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

// The promptForPushNotificationsWithUserResponse function will show the iOS push notification prompt. We recommend removing the following code and instead using an In-App Message to prompt for notification permission
await OneSignal.shared.promptUserForPushNotificationPermission(fallbackToSettings: true);

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();

Step 6 - Run your app and send yourself a notification

Build and test your app to make sure your device is successfully subscribed to notifications and that you can receive notifications sent from the OneSignal dashboard.

📘

Problems/Errors?

If you are having trouble with our SDK, please see our troubleshooting guide

Step 7 - Implement a Soft-Prompt In-App Message for iOS

Android devices are subscribed to notifications automatically when your app is installed, so this section only applies to your iOS release.

Apple's Human Interface Guidelines recommend that apps "Create an alert, modal view, or other interface that describes the types of information they want to send and gives people a clear way to opt in or out."

OneSignal provides an easy option for a "soft-prompt" using In-App Messages to meet this recommendation and have a better user experience. This also permits you to ask for permission again in the future, since the native permission prompt can no longer be shown in your app if the user clicks deny.

See our iOS Push Opt-In Prompt for details on implementing this.

Step 8 - Implement other OneSignal Features

  • Notification Delivery Settings - Learn about the many customizations and methods you can use to send notifications to your users in our Sending Push Messages guide.

  • Automated Messages - Set up Automated Messages to automatically re-engage app users who have lapsed or abandoned their cart. Learn more in our Automated Messages guide.

  • Segments and Tags - OneSignal supports simple and powerful tagging and segmentation to send messages to relevant users through our dashboard and API. Learn more in our Segments guide.

  • In-App Messages - OneSignal supports In-App Messaging in order to display rich content to your users or to present permission prompts, surveys, promotions, announcements, and more. Learn more in our In-App Messaging Overview.

  • E-Mail Support - OneSignal supports the delivery and automation of e-mail in addition to push notifications. Learn more in our Email Overview.

  • Flutter SDK API - Explore other methods available in our Flutter SDK API Documentation.

  • Remote API - Send notifications, import data, and export data using our simple and powerful API. Learn more in our OneSignal API overview..

Updated 2 months ago


Flutter SDK Setup


Instructions for adding the OneSignal Flutter SDK to your Flutter app for iOS and Android

Suggested Edits are limited on API Reference Pages

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