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

iOS Requirements

  • An iOS device (iPhone, iPad, iPod Touch) to test on. The Xcode simulator doesn't support push notifications so you must test on a real device.
  • A Mac with Xcode 12+.
  • An iOS Push Certificate.

Android Requirements

Amazon & Huawei Requirements

Follow these instructions if your app is distributed on the Amazon AppStore and/or the Huawei AppGallery.

πŸ“˜

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
  • 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: ^3.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
  pod 'OneSignalXCFramework', '>= 3.4.3', '< 4.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];
    
    //If your SDK version is < 3.5.0 uncomment and use this code:
    /*
    [OneSignal didReceiveNotificationExtensionRequest:self.receivedRequest
                       withMutableNotificationContent:self.bestAttemptContent];
    self.contentHandler(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];
    
    // Uncomment this line to set the default log level of NSE to VERBOSE so we get all logs from NSE logic
    //[OneSignal setLogLevel:ONE_S_LL_VERBOSE visualLevel:ONE_S_LL_NONE];
    [OneSignal didReceiveNotificationExtensionRequest:self.receivedRequest
                       withMutableNotificationContent:self.bestAttemptContent
                                   withContentHandler:self.contentHandler];
}

- (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
        self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        
        if let bestAttemptContent = bestAttemptContent {
            //If your SDK version is < 3.5.0 uncomment and use this code:
            /*
            OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: self.bestAttemptContent)
            contentHandler(bestAttemptContent)
            */
            
            /* DEBUGGING: Uncomment the 2 lines below to check this extension is excuting
                          Note, this extension only runs when mutable-content is set
                          Setting an attachment or action buttons automatically adds this */
            //OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)
            //bestAttemptContent.body = "[Modified] " + bestAttemptContent.body
            
            OneSignal.didReceiveNotificationExtensionRequest(self.receivedRequest, with: bestAttemptContent, withContentHandler: self.contentHandler)
        }
    }
    
    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 5. Set up OneSignal for 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.10, 0.99.99]'
    }
}

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

Step 6. Initialize the OneSignal SDK (All Platforms)

6.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.setAppId("YOUR_ONESIGNAL_APP_ID");

// 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
OneSignal.shared.promptUserForPushNotificationPermission().then((accepted) {
    print("Accepted permission: $accepted");
});

6.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.setNotificationWillShowInForegroundHandler((OSNotificationReceivedEvent event) {
  // Will be called whenever a notification is received in foreground
  // Display Notification, pass null param for not displaying the notification
        event.complete(event.notification);                                 
});

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

6.3 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 7. Run Your App and Send Yourself a Notification

Run your app on a physical device to make sure it builds correctly. Note that the iOS Simulator does not support receiving remote push notifications.

  • Android devices should be subscribed to push notifications immediately upon opening the app.
  • iOS devices should be prompted to subscribe to push notifications if you used the example setup code provided.

Check your OneSignal Dashboard Audience > All Users to see your Device Record.

Then head over to Messages > New Push to Send your first Push Notification from OneSignal.

πŸ“˜

Troubleshooting

If you run into any issues please see our Flutter troubleshooting guide.

You can find a fully implemented example project on our Github repository.

If stuck, feel free to contact [email protected] for assistance.

Step 8. Implement a Soft-Prompt In-App Message for iOS

Optional

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.

πŸ‘

Setup Complete!

Visit Mobile Push Tutorials for next steps.

Updated 6 days 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.