Dominic
Dominic

Reputation: 31

Push Notifications for Swift iOS 10

I'm struggling to get push notifications to work with Swift with iOS 10. Registering seems to be going through successfully, but creating a notificaiton does nothing on the device and returns a nil error. Any ideas what I'm missing?

import Foundation
import UIKit
import UserNotifications
class SPKPushNotifications
{
    class func register(application:UIApplication){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
                // Enable or disable features based on authorization.
                application.registerForRemoteNotifications()
            }
        } else {
            let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound]
            let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
            application.registerUserNotificationSettings(pushNotificationSettings)
            application.registerForRemoteNotifications()
        }
    }
    class func unregister(application:UIApplication){
        application.unregisterForRemoteNotifications()
    }
    class func create(title:String, body:String, delay:Double, repeats:Bool){
        if #available(iOS 10.0, *) {
            let content = UNMutableNotificationContent()
            content.title = title
            content.body = body
            content.sound = UNNotificationSound.default() //idk if we're gonna want something else
            content.badge = NSNumber(value:UIApplication.shared.applicationIconBadgeNumber+1)
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval:delay, repeats:repeats)
            let request = UNNotificationRequest(identifier:title, content:content, trigger:trigger)
            let center = UNUserNotificationCenter.current()
            center.add(request){ (error) in
                print(error)
            }

        } else {
            // Fallback on earlier versions
        }
    }
    class func delete(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.removeAllDeliveredNotifications()
        } else {
            // Fallback on earlier versions
        }
    }
}

Upvotes: 1

Views: 400

Answers (1)

little
little

Reputation: 3029

You won't see the notification if the application is in the foreground. Try adding the request to the notification center when the application is in the background.

You can do (for this test only) that by adding a few second sleep and moving your application to the background. Or scheduling the notification to a later time when the application is not running in the foreground.

Upvotes: 0

Related Questions