Мой код ниже запускает уведомление, как и должно, когда приложение используется. Однако, когда я выхожу из приложения, уведомление не появляется. Я перечислил как контроллер представления, так и код делегата приложения. Мне показалось, что я ввел правильный код в 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)
}
}
ПРИЛОЖЕНИЕ
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:.
}
}