1
votes

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

2

2 Answers

0
votes

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)
}
0
votes

You are declaring a variable as explicit.

var notificationcenter:NSUserNotificationCenter

That means it can not be nil.

But this

NSUserNotificationCenter.defaultUserNotificationCenter()

can fail, meaning it then returns nil.


Try this

var notificationcenter: NSUserNotificationCenter? = NSUserNotificationCenter.defaultUserNotificationCenter()

Your var is then optional, it now may be set to nil.