【发布时间】:2017-04-20 12:00:41
【问题描述】:
我正在尝试在单击按钮时发送通知。这是我的 viewController 中的代码:
@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()
附:我已经导入了
import UserNotifications
在 AppDelegate 和自定义 ViewController 中。
【问题讨论】:
-
您设置通知的方式会立即触发。你甚至没有时间关闭你的应用程序。如果您的应用甚至不在后台,您如何期望收到通知?
-
useyourloaf.com/blog/local-notifications-with-ios-10 参考这一切步骤它工作正常。
-
import UserNotifications import this 并声明 this 代表 UNUserNotificationCenterDelegate 并将其添加到 didFinishLaunchingWithOptions 方法中 let center = UNUserNotificationCenter.current() center.delegate = self return true
-
还要检查您是否有权接收上升通知。别忘了检查这个。
标签: ios swift swift3 localnotification