3
我試圖通過點擊按鈕發送通知。這是我的viewController代碼:我已經要求使用通知權限本地通知swift 3
@IBAction func getNotificationButtonPressed(_ sender: Any) {
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.categoryIdentifier = "ident"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)
let request = UNNotificationRequest(identifier: "ident", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
} else {
print ("success")
}
}
}
也AppDelegate中:
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization.
}
application.registerForRemoteNotifications()
附:我已經在AppDelegate和自定義ViewController中導入了
import UserNotifications
。
您設置通知的方式會立即啓動。你甚至沒有時間關閉你的應用程序。如果您的應用程序甚至不在後臺,您希望如何收到通知? –
https://useyourloaf.com/blog/local-notifications-with-ios-10/參考這一切步驟其工作正常。 –
進口UserNotifications導入,並宣佈該該代表UNUserNotificationCenterDelegate和 在didFinishLaunchingWithOptions方法中添加此 讓中心= UNUserNotificationCenter.current() center.delegate =自 還真 –