ios - 我无法让本地通知在 xcode 模拟器上的设定时间显示

标签 ios swift xcode uilocalnotification simulator

我对编码相当陌生,想知道如何做到这一点或者我的代码是否有问题。我最初将其设置为在模拟器接受通知后十秒关闭,但实际通知也不会在那里关闭。

import UIKit
import UserNotifications

class ViewController: UIViewController {

  override func viewDidLoad() {
      super.viewDidLoad()

     // Do any additional setup after loading the view.
      let center = UNUserNotificationCenter.current()
      center.requestAuthorization(options: [.alert, .sound])
          { (granted, error) in

      }
      let content = UNMutableNotificationContent()
      content.title = "Prevent nosocomial infections!"
      content.body = "Make sure to do hand hygiene"
      content.sound = .default

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

      let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
      let uuidString = UUID().uuidString
      let request = UNNotificationRequest(identifier: uuidString, content: content, trigger: trigger)

      center.add(request) { (error) in
      }
    }
}

最佳答案

I initially had it set to go off ten seconds after notifications were accepted by the simulator

不,那不是你正在做的事情。 center.requestAuthorization 异步返回其值。因此,您尝试在用户接受通知之前安排通知:对话框仍处于打开状态,询问通知,同时您可以直接继续执行代码。显然这是行不通的,因为通知尚未被接受。您需要将该代码移至 requestAuthorization 的(当前为空)完成处理程序中。

关于ios - 我无法让本地通知在 xcode 模拟器上的设定时间显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59919922/

相关文章:

ios - HLS 视频无法在模拟器和真实设备上播放

ios - 降级到 iOS 5 后启动崩溃

ios - 为 Facebook Messenger iPhone App 实现 UIActivity 子类?

ios - 在 numberOfSectionsInTableView 中使用 NSFetchedResultsController 对日期进行分组

ios - Swift:使用 firebase SDK 时使用未解析的标识符 'FDataSnapShot'

ios - 如何为 UIButton 设置自定义背景颜色?

iOS - swift 3 - DispatchGroup

XCode 中的 iPhone jQuery mobile + PhoneGap .. 具有用于多个 View /页面的多个 html 文件

ios - Swift 应用程序在打开后退出,在 Xcode 中运行

mysql - 直接从 iPad 应用程序连接到 MySQL(不通过 PHP 等)