|

|  How to Send Push Notifications with OneSignal API in Swift

How to Send Push Notifications with OneSignal API in Swift

October 31, 2024

Learn how to send push notifications with OneSignal API in Swift. This guide offers a step-by-step process to easily integrate and manage notifications.

How to Send Push Notifications with OneSignal API in Swift

 

Integrate OneSignal SDK into Your Swift Project

 

  • Open your Xcode project and, through Swift Package Manager, add the OneSignal SDK repository URL to your project dependencies. This ensures that you have the latest version integrated.
  •  

  • Import OneSignal into your AppDelegate or SceneDelegate file: `import OneSignal`.

 

Configure App Delegate for OneSignal

 

  • In your AppDelegate, configure OneSignal when the app launches. This usually involves initializing OneSignal with your app ID provided by the OneSignal dashboard:
func application(_ application: UIApplication, 
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    OneSignal.initWithLaunchOptions(launchOptions, 
                                    appId: "your-app-id", 
                                    handleNotificationAction: nil, 
                                    settings: [kOSSettingsKeyAutoPrompt: false])
    return true
}

 

  • Ensure that your app requests permission to send push notifications. This needs to be handled in the app settings or explicitly through OneSignal:
OneSignal.promptForPushNotifications(userResponse: { accepted in
    print("User accepted notifications: \(accepted)")
})

 

Testing Push Notifications

 

  • Verify your device is registered with OneSignal by checking the Devices section in the OneSignal dashboard. This confirms that your setup is correct.
  •  

  • To test sending a notification via the OneSignal API, prepare your server-side code. For a simple example, using a curl request in the command line might suffice:
curl --include --request POST https://onesignal.com/api/v1/notifications \
--header "Content-Type: application/json; charset=utf-8" \
--header "Authorization: Basic YOUR_REST_API_KEY" \
--data-binary '{
  "app_id": "your-app-id",
  "contents": {"en": "Test message"},
  "include_player_ids": ["device_id"]
}'

 

  • For a Swift-based server or integration into a service, you can use URLSession to send POST requests to the OneSignal API endpoint as demonstrated above.

 

Handle Notification Actions in Swift

 

  • Configure the handling of notification interactions. OneSignal provides a callback that allows you to define custom actions when a notification is opened:
OneSignal.setNotificationWillShowInForegroundHandler { notification, completion in
    // Decide what to do with the notification
    let shouldShowNotification = true
    completion(notification, shouldShowNotification)
}

OneSignal.setNotificationOpenedHandler { result in
    // Called when a notification is tapped on
    print("Notification opened: \(result?.notification.description ?? "")")
}

 

Debugging Common Issues

 

  • If notifications are not received, ensure your app has the correct permissions and is built with a provisioning profile that supports push notifications.
  •  

  • Check device logs for errors related to OneSignal. Use `Console` in Xcode to capture iOS-specific errors.
  •  

  • Verify the REST API connectivity from your server and ensure the API key and app ID used are correct.