I am trying to figure out how to setup a UILocalNotification in swift but I am not having a lot of luck. I am trying this:
var notification = UILocalNotification()
notification.timeZone = NSTimeZone.defaultTimeZone()
var dateTime = NSDate.date()
notification.fireDate(dateTime)
notification.alertBody("Test")
UIApplication.sharedApplication().scheduleLocalNotification(notification)
For starters, I am not sure if this is the proper way to get the current date time. In .Net, I would just do DateTime.Now().
Second, when I try this, I get an error that says:
'(@lvalue NSDate!) -> $T3' is not identical to 'NSDate'
Unfortunately I have no idea what this means or how to proceed.
In Swift, to cancel the particular local notification using Unique Key:
Not answering your question but worth the note:
will also throw a compiler error saying that it can't find the init. do this instead
There's also support for creating the date like so:
First, you construct an
NSDate
using initializer syntax:The documentation shows how ObjC convenience constructors map to Swift initializers. If the docs show an
init()
for a class, you call it using the name of the class: forNSDate
,init()
means you callNSDate()
,init(timeInterval:sinceDate:)
means you callNSDate(timeInterval: x, sinceDate: y)
, etc.Second:
fireDate
isn't a method, it's a property. You should assign to it instead of trying to call it:Ditto for
alertBody
.You can also find the Swift syntax for Cocoa APIs by command-clicking a class name (or other API symbol) in your Swift source file; this causes Xcode to generate a "Swift-ified" version of the relevant header file.
Would be nice to also separate out some of the components:
Now you can call,
ScheduleLocalNotificationIfPossible()
to schedule the local notification if the user has registered for remote notifications.