当应用程序在后台运行时,不会出现swift 4通知

时间:2018-12-28 03:40:04

标签: ios push-notification notifications swift4 appdelegate

以下我的代码正在触发通知,通知使用该应用程序时的状态。但是,当我退出该应用程序时,该通知不会出现。我已经列出了我的视图控制器和应用程序委托代码。我以为我在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:.
    }


}

1 个答案:

答案 0 :(得分:0)

我已经用静态时间检查过您的代码,并且当应用程序处于后台时,我会收到通知。为了使您更好地理解,我只更改了代码中的一件事。

将此代码放入AppDelegate的n = int(input('Please enter an integer')) s = 1 do: print(s) s+=1 while s == n 方法中以用于请求。

didFinishLaunchingWithOptions

还要在AppDelegate中分配 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 委托。

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

UNUserNotificationCenterDelegate

现在检查静态时间,当应用程序在前景中以及应用程序在背景中时,您也会收到通知。如果它可以正常工作,那么您选择的时间应该有问题。