应用程序在后台时没有出现swift 4通知

Posted

技术标签:

【中文标题】应用程序在后台时没有出现swift 4通知【英文标题】:swift 4 notification not appearing when app is in background 【发布时间】:2018-12-28 03:40:03 【问题描述】:

我下面的代码在应用程序正在使用时以应有的方式触发通知。但是,当我退出应用程序时,通知不会出现。我已经列出了我的视图控制器和应用程序委托代码。我以为我在 App Delegate 中放置了正确的代码。我不确定为什么这不起作用。

查看控制器

   import UIKit
import AVFoundation
import UserNotifications

let center = UNUserNotificationCenter.current() // usernotification center

class ViewController: UIViewController, UNUserNotificationCenterDelegate 
    var timer = Timer()
    var isGrantedAccess = false
    var player: AVAudioPlayer?
    var passingDate : Date?
    @IBOutlet var dptext: UITextField!
    let datePicker = UIDatePicker()
    @IBOutlet var taskIDo: UITextView!

    override func viewWillAppear(_ animated: Bool) 

        center.delegate = self
        createDatePicker()
        timer  = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(testDate), userInfo: nil, repeats: true)

    

    func playSound() 
        let url = Bundle.main.url(forResource: "fc", withExtension: "mp3")!
        do 
            player = try AVAudioPlayer(contentsOf: url)
            guard let player = player else  return 

            player.prepareToPlay();player.play() catch let error as NSError print(error.description)


    func createDatePicker() 
        datePicker.datePickerMode = .dateAndTime
        let toolbar = UIToolbar()
        toolbar.sizeToFit()

        let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
        toolbar.setItems([doneButton], animated: false)

        dptext.inputAccessoryView = toolbar;dptext.inputView = datePicker
    

    @objc func testDate() 
        print("in testDate")
        if Calendar.current.isDate(datePicker.date, equalTo: Date(), toGranularity: .minute) 
            if let passingDate = passingDate, Calendar.current.isDate(datePicker.date, equalTo: passingDate, toGranularity: .minute)
            
                print("in return")
                return
            

            passingDate = datePicker.date

            setNotification()

        
    
    func setNotification() 
        let content = UNMutableNotificationContent()
        content.title = "This is Title"
        content.subtitle = "This is subTitle"

        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)

        let request = UNNotificationRequest(identifier: "Identifier", content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request)  (error) in

            print(error?.localizedDescription ?? "")
        

    
    @objc func donePressed() 

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .short
        dateFormatter.timeStyle = .short
        dptext.text = dateFormatter.string(from: datePicker.date)
        self.view.endEditing(true)

    

APPDELEGATE

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate 

    var window: UIWindow?



    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool 
        // Override point for customization after application launch.

        UNUserNotificationCenter.current().requestAuthorization(options:
            [.badge,.alert,.sound])
        
            (sucess,error) in
            if error != nil 
                print("Error Found, \(error?.localizedDescription ?? "")")

             else 
                print("Authorized by the user")
            
        

        UNUserNotificationCenter.current().delegate = self
        return true
    

    func applicationWillResignActive(_ application: UIApplication) 
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    

    func applicationDidEnterBackground(_ application: UIApplication) 
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    

    func applicationWillEnterForeground(_ application: UIApplication) 
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    

    func applicationDidBecomeActive(_ application: UIApplication) 
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    

    func applicationWillTerminate(_ application: UIApplication) 
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    



【问题讨论】:

local notification not appearing (Swift4)的可能重复 【参考方案1】:

我用静态时间检查了你的代码,当应用程序处于后台时我会收到通知。为了更好地理解,我刚刚更改了代码中的一件事。

将此代码放入请求的 AppDelegate 的 didFinishLaunchingWithOptions 方法中。

 UNUserNotificationCenter.current().requestAuthorization(options:  
  [.badge,.alert,.sound])
    
        (sucess,error) in
        if error != nil 
            print("Error Found, \(error?.localizedDescription ?? "")")

         else 
            print("Authorized by the user")
        
    

    UNUserNotificationCenter.current().delegate = self

同时在 AppDelegate 中分配 UNUserNotificationCenterDelegate 委托。

现在在您的 viewController 中添加此函数并根据需要调用它。

 func setNotification() 
    let content = UNMutableNotificationContent()
    content.title = "This is Title"
    content.subtitle = "This is subTitle"

    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10.0, repeats: false)

    let request = UNNotificationRequest(identifier: "Identifier", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request)  (error) in

        print(error?.localizedDescription ?? "")
    


现在检查静态时间,当应用程序处于前台以及应用程序处于后台时,您会收到通知。如果它有效,那么您的时间选择应该有问题。

【讨论】:

我已经在上面的视图控制器和应用程序委托中添加了我的所有代码。当我在 iPad 上打开我的应用程序时,我收到了发送通知的请求授权,但即使我在添加和设置计时器时也看不到任何通知。 你添加了静态时间吗?比如10秒后通知?看看我的例子,我已经使用了你的代码及其工作,所以只需尝试使用静态时间并检查它是否工作

以上是关于应用程序在后台时没有出现swift 4通知的主要内容,如果未能解决你的问题,请参考以下文章

Swift - 在后台在应用程序中接收本地通知时执行功能

推送通知无法正常工作,当应用程序在后台时,Swift

应用程序在后台时的远程推送通知 swift 3

应用程序在后台运行时发送本地通知 Swift 2.0

使用swift后台获取本地通知

在 Swift iOS 中推送通知