Search code examples
macosnotificationsswiftcenter

Swift NotificationCenter Can't unwrap Optional.None


I'm programming simple program i want show notification on mac os x

this is my code

import Foundation
import Cocoa

var notification:NSUserNotification = NSUserNotification()
notification.title = "TEST"
notification.subtitle = "TTTT"


var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()
if(notificationcenter != nil) {
    notificationcenter.scheduleNotification(notification)
}

that code build succeeded but when stop running code

fatal error: Can't unwrap Optional.None

var notificationcenter:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()

what can i do


Solution

  • You get this because you try unwrap optional which can be nil, you can do it like that:

    if let notificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter() {
        notificationcenter.scheduleNotification(notification)
    }