我是 Swift 和 XCode 編程的新手,我在除錯代碼時遇到了麻煩。該應用程式應該每天在同一時間向用戶發送一次通知。到目前為止,我已經設定了基礎知識,但是在測驗時,如果我清除應用程式并重新打開它,它會安排兩個通知而不是一個通知。我需要某種魔術來解決這個問題嗎?
目前,scheduleNotification正在呼叫該函式,viewDidLoad以便它可以在啟動后立即安排所有內容。我試過在UNUserNotificationCenter.current().add(request). 我認為在下面呼叫它是有意義的,因為它只提示用戶一次,所以當用戶授予通知權限時,它會立即激活通知,而不會有重復的風險。但這根本沒有安排任何通知。
我做了更多研究,也許我將通知編程到錯誤的檔案中?這一切都在視圖控制器中。
我和我父親談過,他非常喜歡軟體,他建議用 ID 跟蹤通知,如果我不希望它們出現,就洗掉它們。但這聽起來很復雜,我不想再頭痛了哈哈
有任何想法嗎?
(另外,忽略一些與計算器有關的呼叫。這與我的問題無關)
//
// ViewController.swift
//
import UIKit
class ViewController: UIViewController {
// Calculator Outlets
@IBOutlet weak var calculatorWorkings: UILabel!
@IBOutlet weak var calculatorResults: UILabel!
var workings:String = ""
override func viewDidLoad() {
super.viewDidLoad()
clearAll()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {_, _ in
DispatchQueue.main.asyncAfter(deadline: .now() 1) {
print("Request authorized")
// Repeatedly call function so program schedules notifications in advance
for i in 1...10 {
self.scheduleNotification(day: i)
}
}
}
}
// Phrases
let phrasesArray = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
// Handle Notifications
func scheduleNotification(day: Int) {
var dateComponents = DateComponents()
dateComponents.hour = 21
dateComponents.minute = 09
dateComponents.day = day
let content = UNMutableNotificationContent()
// App name is not included in notification bar
content.title = "Jenna's Wisdom:"
content.body = phrasesArray[(Int.random(in: 0..<9))]
content.sound = .default
content.interruptionLevel = .timeSensitive
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
// Request to send notifications
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print(error)
} else {
print("Success")
}
}
}
}
uj5u.com熱心網友回復:
假設 ViewController 是第一個和 rootViewcontroller,您可以在添加新通知之前洗掉所有本地通知。
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449588.html
