Local Notifications make sound but do not display (Swift)

前端 未结 3 924
死守一世寂寞
死守一世寂寞 2021-01-13 10:38

I am trying to create a local notification for my app using Apple\'s UNUserNotificationCenter.

Here is my code:

let center = UNUserNotificationCenter         


        
相关标签:
3条回答
  • 2021-01-13 10:44

    Add this code into didFinishLaunchingWithOption in AppDelegate.swift file

    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) 
    { (granted, error) in
    // Enable or disable features based on authorization.
    }
    
    0 讨论(0)
  • 2021-01-13 10:56

    Add this Protocoal UNUserNotificationCenterDelegate. and add this delegate into your controller. and dont forget to set delegate.

    UNUserNotificationCenter.current().delegate = self
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            print("Notification being triggered")
            //You can either present alert ,sound or increase badge while the app is in foreground too with ios 10
            //to distinguish between notifications
            if notification.request.identifier == "yourrequestid"{
                completionHandler( [.alert,.sound,.badge])
            }
        }
    
    0 讨论(0)
  • 2021-01-13 11:06

    I had the same problem.

    If your content body is blank ie(content.body == "") then you won't get a notification even if you do have a title.

    So the solution is to make sure that your content body is not an empty string.

    0 讨论(0)
提交回复
热议问题