【问题标题】:Get local notification when App is in foreground Swift 4 iOS 11应用程序在前台时获取本地通知 Swift 4 iOS 11
【发布时间】:2018-06-14 00:36:26
【问题描述】:

我想在我的应用程序处于前台时接收本地通知,当我尝试使用以下代码时它从不触发通知,但是当我在后台进入应用程序时它确实触发了。

这是我尝试过的:

//Schedule a Local Notification
func ScheduleNotification(timeInterval: Double, repeats: Bool, notificationBody:String, title:String){

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: repeats)

    let center = UNUserNotificationCenter.current()

    let identifier = "UYLLocalNotification"
    let content = UNMutableNotificationContent()
    content.title = title
    content.body = notificationBody
    content.sound = UNNotificationSound.default()
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    center.add(request, withCompletionHandler: { (error) in
        if let error = error {
            //Something went wrong
            print(error.localizedDescription)
        }
    })
}

override func viewDidLoad() {
    super.viewDidLoad()

    if Currentcount < data.count {
        self.ScheduleNotification(timeInterval: 5.0, repeats: false, notificationBody: "You have \(data.count - Currentcount) notification", title: "Alert!")
    }
}

任何帮助将不胜感激 谢谢。

【问题讨论】:

    标签: ios swift uilocalnotification


    【解决方案1】:

    当您的应用程序处于前台时,通知可能也会触发。

    默认情况下,当通知到达并且目标应用程序位于前台时,iOS 不会显示任何 UI。显示通知内容是应用程序的工作。使用UNUserNotificationCenterDelegate,您可以非常轻松地将通知显示为警报。请参阅this post 了解更多信息。

    【讨论】:

    • 是否需要在 viewDidLoad() 方法中添加任何内容?
    【解决方案2】:

    这里我将逐步向您展示 UNUserNotificationCenterDelegate 是如何工作的

    1. 在 AppDelegate 中:import UserNotifications

    2. class AppDelegate: UIResponder,UNUserNotificationCenterDelegate{}

    3. didFinishLaunchingWithOptions

      中将委托方法分配给self
      func application(_application:UIApplication,
      didFinishLaunchingWithOptionslaunchoptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      
             UIApplication.shared.applicationIconBadgeNumber = 0
                  let center = UNUserNotificationCenter.current()
                  center.delegate = self        
                  center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
      
                      if granted {
                          DispatchQueue.main.async { // Correct
                              UIApplication.shared.registerForRemoteNotifications()
                          }
      
                      }
      
                  }
      
          }
      
    4. 您想在本地通知中显示的内容

           func assignValueToNotification
              {
                  let content = UNMutableNotificationContent()
                  content.body = "Asssign body"
                  content.userInfo = ["identifier": "info"]
                  content.sound = UNNotificationSound.default()
                  content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber;
                  content.categoryIdentifier = "write category identifier"
                  // Deliver the notification in five seconds.
                  let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.5, repeats: false)
                  let request = UNNotificationRequest.init(identifier: region.identifier as String, content: content, trigger: trigger)
                 // Schedule the notification.
                 let center = UNUserNotificationCenter.current()
                 center.add(request)
          }
      
    5. 写下你的委托方法,当你点击本地通知时将被调用。

      func userNotificationCenter(_ center:UNUserNotificationCenter, didReceive response:UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void{
          print("Received Local Notification:")
      }
      

    【讨论】:

    • 欢迎使用 StackOverflow:如果您发布代码、XML 或数据示例,请在文本编辑器中突出显示这些行,然后单击编辑器工具栏上的“代码示例”按钮 ( { } ) 或使用 Ctrl键盘上的 +K 可以很好地格式化和语法突出显示它!
    【解决方案3】:

    您可以简单地将UNUserNotificationCenterDelegatewillPresent 委托函数添加到您的AppDelegate

    只需将.sound, .bannerUNNotificationPresentationOptions 提供给完成处理程序,您的本地通知就会在您的应用处于前台时显示。

    extension AppDelegate: UNUserNotificationCenterDelegate {
        
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            completionHandler([.sound, .banner])
        }
    }
    

    还有一步:你当然需要在didFinishLaunchingWithOptions 中设置UNUserNotificationCenter 委托。

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {  
        UNUserNotificationCenter.current().delegate = self
    }
    

    注意

    对于 SwiftUI Cycles,您可以像这样访问 AppDelegate: Here

    【讨论】:

      猜你喜欢
      • 2017-02-04
      • 2013-01-30
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多