App位于前景Swift 4 iOS 11时获取本地通知

时间:2018-01-04 09:47:34

标签: ios swift uilocalnotification

我希望在我的应用处于前台时收到本地通知,当我尝试使用以下代码时,它从不会触发通知,但当我在后台输入应用时,它确实被解雇了。

这是我试过的:

//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!")
    }
}

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

3 个答案:

答案 0 :(得分:2)

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

默认情况下,当通知到达并且目标应用程序位于前台时,iOS不会显示任何UI。显示通知内容是应用程序作业。使用UNUserNotificationCenterDelegate,您可以非常轻松地将通知显示为提醒。有关详细信息,请参阅this post

答案 1 :(得分:1)

我在这里向您展示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:")
    }
    

答案 2 :(得分:0)

您只需将willPresent的{​​{1}}委托函数添加到您的UNUserNotificationCenterDelegate

只需将AppDelegate .sound, .banner赋予完成处理程序,您的本地通知就会在您的应用程序位于前台时显示。

UNNotificationPresentationOptions

又一步:您当然需要在extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.sound, .banner]) } } 内设置UNUserNotificationCenter委托。

didFinishLaunchingWithOptions

注意

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