通知无法在iOS 12上启动

时间:2019-06-01 20:01:15

标签: ios swift

我试图将自己的快速代码转换为支持IOS 10及更高版本,但没有得到任何通知,这是我的代码

let content = UNMutableNotificationContent()
content.title = "tried"
content.subtitle = "wg"
content.body = "any body"
content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "name.caf"))

let calendar = Calendar(identifier: .gregorian)

let components = calendar.dateComponents(in: .current, from: date)
let newComponents = DateComponents(calendar: calendar, timeZone: .current,year: components.year , month: components.month, day: components.day, hour: components.hour, minute: components.minute)
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)

我打印待处理的通知,有待处理的通知但未触发

<UNNotificationRequest: 0x60000314d650; identifier: C8BC936E-AD9B-4D7A-94D3-52D3233DE281, content: <UNNotificationContent: 0x600000ad8780; title: tried, subtitle: wg, body: any body, summaryArgument: , summaryArgumentCount: 0, categoryIdentifier: , launchImageName: , threadIdentifier: , attachments: (
), badge: (null), sound: <UNNotificationSound: 0x600001bdb900>,, trigger: <UNCalendarNotificationTrigger: 0x600003f511a0; dateComponents: <NSDateComponents: 0x6000008fd550>
    Calendar: <_NSCopyOnWriteCalendarWrapper: 0x600003f51240>
    TimeZone: Asia/Riyadh (GMT+3) offset 10800
    Calendar Year: 2019
    Month: 6
    Day: 22
    Hour: 8
    Minute: 5, repeats: NO>> 

2 个答案:

答案 0 :(得分:0)

这是在5秒钟后获得本地通知的最小工作示例。

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func applicationDidFinishLaunching(_ application: UIApplication) {

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { [weak self] didAllow, error in
     // For testing purpose, expected permissions are allowed.
      self?.scheduleNotificationAfter5Seconds()
    })
  }

  func scheduleNotificationAfter5Seconds() {
    //creating the notification content
    let content = UNMutableNotificationContent()

    //adding title, subtitle, body and badge
    content.title = "tried"
    content.subtitle = "wg"
    content.body = "any body"
    content.badge = 1

    //getting the notification trigger
    //it will be called after 5 seconds
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

    //getting the notification request
    let request = UNNotificationRequest(identifier: "notification", content: content, trigger: trigger)

    //adding the notification to notification center
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
  }
}

与您的代码一起发布的是用于创建触发器的日期。您必须创建要触发通知的正确日期。

答案 1 :(得分:0)

如果通知时间为同一天

,如果给IOS提供完整的日期,我发现IOS没有安排通知

如果同一天的通知,您只需给它小时和分钟