2016-11-30 49 views
4

我有一个包含我的日期的数组。我想在上午6点30分安排那些日子的通知。使用Swift 3为日期数组安排通知

我跟着appcoda tutorial它帮助安排通知从日期选择器输入很好,但我有点不确定如何调用我的函数安排通知只有给定的日子。

所以我的问题是如何以及在哪里调用该函数?

  • 的日子已经连续多日
  • 我可以给该函数的开始日期,并在阵列中的项目数重复一次吗?

下面是我的函数:

func scheduleNotification(at date: Date) { 
     let calendar = Calendar(identifier: .gregorian) 
     let components = calendar.dateComponents(in: .current, from: date) 
     let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: 6, minute: 30) 
     let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false) 

     let content = UNMutableNotificationContent() 
     content.title = "Advent Calendar" 
     content.body = "Just a reminder to open your present!" 
     content.sound = UNNotificationSound.default() 

     let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger) 
UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 
     UNUserNotificationCenter.current().add(request) {(error) in 
      if let error = error { 
       print("Uh oh! We had an error: \(error)") 
      } 
     } 
    } 

回答

1

权,因此与开发商@gklka协商后,我决定用一个简单的循环,重复24次),并将它传递的指数函数的一天物业,在那里我预先配置的小时,分​​钟,年份和月份,像这样:

func scheduleNotification(day: Int) { 

    var date = DateComponents() 
    date.year = 2016 
    date.month = 11 
    date.day = day 
    date.hour = 6 
    date.minute = 30 

    let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false) 
} 

和for循环:

for index in 1...24 { 
     scheduleNotification(day: index) 
    } 

自从我拥有了一切设置INT的AppDelegate我称之为didFinishLaunchingWithOptions

更新的功能在12月

一号所以我离开的一切,只不过是没有通知发生在上午。 。我查看了我的代码,找出原因。有两个问题。

  1. 我有我的函数中的代码行,将删除任何先前的通知设置,同时通过我的循环迭代,所以我有以下行注释掉的代码,但事情仍然没有按预期工作。 UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

  2. 我发现我用相同的requestIdentifier来安排我的通知,这基本上给我留下了最后一天只有1个通知。我只是增加了索引处用绳子插我的自定义ID变量的末尾,就像这样:let requestId = "textNotification\(day)"

+0

请问这个新的FUNC scheduleNotification与你的问题之前的功能在您创建的通知互动?您的警报内容是否与所有警报 – tylerSF

+0

@tylerSF相同,它会一次创建所有24个通知,计划每天发送一次。该应用程序每天都会包含一项新礼物,因此通知相同,只是为了让用户注意到这些信息。 –