Как использовать UILocalNotification в Swift
Я пытаюсь понять, как настроить UILocalNotification в swift, но мне не очень повезло. Я пробую это:
var notification = UILocalNotification()
notification.timeZone = NSTimeZone.defaultTimeZone()
var dateTime = NSDate.date()
notification.fireDate(dateTime)
notification.alertBody("Test")
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Для начала, я не уверен, что это правильный способ получить текущее время. В .Net я бы просто сделал DateTime.Now().
Во-вторых, когда я пытаюсь это сделать, я получаю ошибку, которая гласит:
'(@lvalue NSDate!) → $T3' не идентичен 'NSDate'
К сожалению, я понятия не имею, что это значит или как действовать.
Ответы
Ответ 1
Сначала вы создаете NSDate
с использованием синтаксиса инициализатора:
let dateTime = NSDate()
Документация показывает, как конструкторы удобства ObjC сопоставляются с инициализаторами Swift. Если docs показывает init()
для класса, вы вызываете его с использованием имени класса: для NSDate
, init()
означает, что вы вызываете NSDate()
, init(timeInterval:sinceDate:)
означает, что вы вызываете NSDate(timeInterval: x, sinceDate: y)
и т.д.
Второе: fireDate
не является методом, это свойство. Вы должны назначить ему вместо того, чтобы называть его:
notification.fireDate = dateTime
То же самое для alertBody
.
Вы также можете найти синтаксис Swift для API Cocoa, нажав на имя имени класса (или другой символ API) в исходном файле Swift; это заставляет Xcode генерировать "Swift-ified" версию соответствующего файла заголовка.
Ответ 2
func setupNotificationReminder() {
var title:String = "Your reminder text goes here"
let calendar = NSCalendar.currentCalendar()
let calendarComponents = NSDateComponents()
calendarComponents.hour = 7
calendarComponents.second = 0
calendarComponents.minute = 0
calendar.timeZone = NSTimeZone.defaultTimeZone()
var dateToFire = calendar.dateFromComponents(calendarComponents)
// create a corresponding local notification
let notification = UILocalNotification()
let dict:NSDictionary = ["ID" : "your ID goes here"]
notification.userInfo = dict as! [String : String]
notification.alertBody = "\(title)"
notification.alertAction = "Open"
notification.fireDate = dateToFire
notification.repeatInterval = .Day // Can be used to repeat the notification
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
Ответ 3
Не отвечая на ваш вопрос, но стоит отметить:
notification.fireDate(dateTime)
notification.alertBody("Test")
также выдает ошибку компилятора, говоря, что он не может найти init. сделайте это вместо
notification.fireDate = NSDate(timeIntervalSinceNow: 15)
notification.alertBody = "Notification Received"
Ответ 4
Там также поддерживается создание такой даты:
NSDate(timeIntervalSinceNow: 15)
Ответ 5
В Swift для отмены конкретного локального уведомления с помощью уникального ключа:
func cancelLocalNotification(UNIQUE_ID: String){
var notifyCancel = UILocalNotification()
var notifyArray = UIApplication.sharedApplication().scheduledLocalNotifications
for notifyCancel in notifyArray as! [UILocalNotification]{
let info: NSDictionary = notifyCancel.userInfo as! [String : String]
if info[UNIQUE_ID]!.isEqual(UNIQUE_ID){
UIApplication.sharedApplication().cancelLocalNotification(notifyCancel)
}else{
println("No Local Notification Found!")
}
}
}
Ответ 6
Было бы неплохо выделить некоторые компоненты:
private let kLocalNotificationMessage:String = "Your message goes here!"
private let kLocalNotificationTimeInterval:NSTimeInterval = 5
private func LocalNotification() -> UILocalNotification {
var localNotification:UILocalNotification = UILocalNotification()
localNotification.fireDate = NSDate(timeIntervalSinceNow:kLocalNotificationTimeInterval)
localNotification.alertBody = kLocalNotificationMessage
return localNotification
}
private func ScheduleLocalNotificationIfPossible() {
if (UIApplication.sharedApplication().isRegisteredForRemoteNotifications()) {
UIApplication.sharedApplication().scheduleLocalNotification(LocalNotification())
}
}
Теперь вы можете позвонить, ScheduleLocalNotificationIfPossible()
, чтобы запланировать локальное уведомление, если пользователь зарегистрировался для удаленных уведомлений.