2016-11-30 31 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個通知,計劃每天發送一次。該應用程序每天都會包含一項新禮物,因此通知相同,只是爲了讓用戶注意到這些信息。 –