2016-12-17 1 views
5

에 대해 하나의 통지 내가 단일 알림을 사용하게하고,이 내 코드입니다 :이 지역 알림을 등록입니다 >>>하지 신속한 3

func registerLocal() { 
    let center = UNUserNotificationCenter.current() 

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in 
     if granted { 
      print("Yay!") 
     } else { 
      print("D'oh") 
     } 
    } 
} 

이 기능 내가 당신을 감사합니다 아이폰 OS (10)와 여러 로컬 통보 및 다른 시간에이 코드를 사용할 수있는 방법을 이제 로컬 통지 >>>

func scheduleLocal() { 
    registerCategories() 

    let center = UNUserNotificationCenter.current() 

    // not required, but useful for testing! 
    center.removeAllPendingNotificationRequests() 

    let content = UNMutableNotificationContent() 
    content.title = "good morning" 
    content.body = "ttt123" 
    content.categoryIdentifier = "alarm" 
    content.userInfo = ["customData": "fizzbuzz"] 
    content.sound = UNNotificationSound.default() 

    var dateComponents = DateComponents() 
    dateComponents.hour = 23 
    dateComponents.minute = 18 
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) 

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) 
    center.add(request) 
} 

func registerCategories() { 
    let center = UNUserNotificationCenter.current() 
    center.delegate = self 

    let show = UNNotificationAction(identifier: "show", title: "Tell me more…", options: .foreground) 
    let category = UNNotificationCategory(identifier: "alarm", actions: [show], intentIdentifiers: []) 

    center.setNotificationCategories([category]) 
} 

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
    // pull out the buried userInfo dictionary 
    let userInfo = response.notification.request.content.userInfo 

    if let customData = userInfo["customData"] as? String { 
     print("Custom data received: \(customData)") 

     switch response.actionIdentifier { 
     case UNNotificationDefaultActionIdentifier: 
      // the user swiped to unlock; do nothing 
      print("Default identifier") 

     case "show": 
      print("Show more information…") 
      break 

     default: 
      break 
     } 
    } 

    // you need to call the completion handler when you're done 
    completionHandler() 
} 

를 예약 할 수 있습니다.

+0

그럼, 당신의 경우에 대한 해결책을 찾았습니까? :) –

답변

4

각 알림마다 다른 요청 식별자를 사용하십시오. 그렇지 않으면 마지막 알림 만 표시됩니다. 위의 예에서 요청 식별자 "UUID() .uuidString"이 각 알림 요청에 대해 고유 한 값을 포함하는지 확인하십시오.

4

다른 dateComponents으로 func scheduleLocal() 번을 여러 번 호출하여 다른 날짜를 예약 할 수 있습니다. 또는이 배열에 날짜 배열을 전달하고 루프를 실행하여이 날짜에 따라 알림을 예약 할 수 있습니다.

UNNotificationRequest(identifier:, content:, trigger:) 함수에서 전달한 식별자가 각 알림마다 다른지 확인하십시오.

희망이 도움이됩니다. :)

2

다른 매개 변수로이 함수를 호출하십시오. 앱이 배경이 될 때 전화 한 것처럼

func applicationDidEnterBackground(_ application: UIApplication) { 

     setNotification(time: 25,identifier: "notific2") 
     setNotification(time: 50,identifier: "notific3") 
     setNotification(time: 90,identifier: "notific4") 
    } 


    func setNotification (time : Int,identifier : String) 
    { 
     let content = UNMutableNotificationContent() 
     content.title = "Don't forget" 
     content.body = "Buy some milk" 
     content.sound = UNNotificationSound.default() 
     let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(time), 
                 repeats: false) 
     let center = UNUserNotificationCenter.current() 
     // Swift 
     let request = UNNotificationRequest(identifier: identifier, 
              content: content, trigger: trigger) 
     center.add(request, withCompletionHandler: { (error) in 
      if error != nil { 
       // Something went wrong 
      } 
     }) 
    } 
0

코드는 예상대로 작동해야합니다. 그러나, 작은 함정이 있습니다.

정확하게 동일한 문제가 발생했다고 생각합니다. 보류중인 알림을 추적하려고 한 후에 추가 된 유일한 알림이 마지막으로 요청한 알림입니다. 당신이 scheduleLocal() 함수 호출하기 때문에 그건 :

// not required, but useful for testing! 
center.removeAllPendingNotificationRequests() 

음,이 불필요한 중복 알림을 방지 도움이 될,하지만 당신은 한 번만scheduleLocal()를 호출하기 전에 를 호출해야 기존 알림 알림 요청을 제거하는 것이 좋다 :

UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 
// now you could call this function many times... 
scheduleLocal() 

간단하게, 당신은 그것을 추가 한 후 직접 각 보류 알림을 삭제하지 않는 대신 전체 이전 보류 알림을 삭제하고 새로 추가합니다.