2017-10-14 64 views
1

如何运行例如本地通知? 在UNUserNotificationCenter中没有重复功能。 也许使用NSTimer或类似的东西?在“A”a.m.和“B”之间每x分钟重复一些操作p.m

为什么如我所料

let hours: [Int] = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] 
    for hour in hours { 
     for minute in stride(from: 0, to: 60, by: 5){ 
      let content = UNMutableNotificationContent() 
      content.title = "Title" 
      content.body = "Body" 

      var dateComponents = DateComponents() 
      dateComponents.hour = hour 
      dateComponents.minute = minute 

      let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) 
      let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger) 
      let center = UNUserNotificationCenter.current() 
      center.add(request) { (error : Error?) in 
       if let theError = error { 
        print(theError.localizedDescription) 
       } 
      } 

     } 
    } 
+0

您可以通过使用'UNTimeIntervalNotificationTrigger'安排在'UNNotificationCenter'重复通知,但你不能确定它将停止在重复一天中的某个时间,然后再次恢复。 – Paulw11

+0

也许[Calendar](https://developer.apple.com/documentation/foundation/calendar)也是一个选项。 – shallowThought

+0

为什么此代码不会每5分钟创建一次通知? 我考虑了更新的答案,但是如果我想在for循环中使用UNCalendarNotificationTrigger,它不会创建通知。 @ Paulw11 – Obarg

回答

2

有一个重复功能我的代码不能正常工作。

Apple's documentation

let content = UNMutableNotificationContent() 
content.title = NSString.localizedUserNotificationString(forKey: 
      "Hello!", arguments: nil) 
content.body = NSString.localizedUserNotificationString(forKey: 
      "Hello_message_body", arguments: nil) 

// Deliver the notification in five seconds and repeat it 
content.sound = UNNotificationSound.default() 
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, 
     repeats: true) 

// Schedule the notification. 
let request = UNNotificationRequest(identifier: "60_seconds", content: content, trigger: trigger) 
let center = UNUserNotificationCenter.current() 
center.add(request, withCompletionHandler: nil) 

编辑:

也如写的文档中,你当然必须有用户权限发布通知:

let center = UNUserNotificationCenter.current() 
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in 
    // Enable or disable features based on authorization 
} 

结果:

通知发布每分钟:

+0

你能检查我的代码为什么不起作用吗? – Obarg

+0

“不起作用”不是一个非常有用的描述。我确实尝试了,在这里按预期工作。查看更新的答案。 – shallowThought

+0

你说得对。它没有按我的预期工作。非常感谢 – Obarg

相关问题