标签: unusernotificationcenter

在iOS 10中使用UNUserNotificationCenterDelegate收到新通知时,如何删除以前发送的通知?

这个问题是关于UserNotificationsiOS 10中的新框架.

我有一个应用程序,在用户在应用程序中执行某个操作后,每隔半小时安排一次本地通知,从1小时开始.

为了避免使用户的锁定屏幕或通知中心混乱,我只希望一次显示一个通知,因此只有一个通知包含最新的相关信息.我实现这一目标的计划是在出现新通知时随时清除所有已发送的通知.

看来这应该是可行的新willPresent方法UNUserNotificationCenterDelegate,但它的行为并不像我期望的那样.

这是一个函数,我打电话设置所有通知,从应用程序中的事件后1小时开始,并在事件发生后23.5小时每半小时安排一次通知,直到最后一个通知:

func updateNotifications() {

    for hour in 1...23 {
        scheduleNotification(withOffsetInHours: Double(hour))
        scheduleNotification(withOffsetInHours: Double(hour) + 0.5)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是根据实际进度通知的功能mostRecentEventDate,这是一个Date集内其他:

func scheduleNotification(withOffsetInHours: Double) {

    // set up a Date for when the notification should fire
    let offsetInSeconds = 60 * 60 * withOffsetInHours
    let offsetFireDate = mostRecentEventDate.addingTimeInterval(offsetInSeconds)

    // set up the content of the notification
    let content = UNMutableNotificationContent()
    content.categoryIdentifier = "reminder"
    content.sound = UNNotificationSound.default()
    content.title = …
Run Code Online (Sandbox Code Playgroud)

notifications ios ios10 unusernotificationcenter

11
推荐指数
1
解决办法
4651
查看次数

iOS 10如何使用UNUserNotificationCenter查看待处理通知列表?

解决方案代码

let center = UNUserNotificationCenter.current()
print(center.getPendingNotificationRequests(completionHandler: { error in
        // error handling here
    }))
Run Code Online (Sandbox Code Playgroud)

我的原帖:

我正在尝试通过UNUserNotificationCenter获取待处理通知的列表UIApplication.shared.scheduledLocalNotifications.

这是我正在使用的代码:

let center = UNUserNotificationCenter.current()
    print(UNUserNotificationCenter.getPendingNotificationRequests(center))
Run Code Online (Sandbox Code Playgroud)

但是这会打印"(功能)".getPendingNotificationRequests需要一个UNUserNotificationCenter参数,我想不出它可能是什么.

谢谢

ios swift3 ios10 unusernotificationcenter

9
推荐指数
1
解决办法
8397
查看次数

访问UNNotificationRequest对象的计划日期

我试图找到UNNotificationRequest对象的预定开火日期.

我正在提取这样的待处理通知请求:

UNUserNotificationCenter.current().getPendingNotificationRequests { (notifications) in

        let pendingNotifications : [UNNotificationRequest] = notifications
    }
Run Code Online (Sandbox Code Playgroud)

然后我尝试访问每个UNNotificationRequest对象的触发日期.

我可以按如下方式访问UNNotificationTrigger,但无法找到访问通知的计划发布日期的方法.

let notification = pendingNotifications[indexOfNotification]
let trigger : [UNNotificationTrigger] = notification.trigger
Run Code Online (Sandbox Code Playgroud)

我已经能够访问一些通知的日期,如下所示:

let date = trigger.value(forKey: "date") as! Date
Run Code Online (Sandbox Code Playgroud)

这适用于使用UNUserNotificationCenter安排的通知,但在尝试访问iOS 10之前安排的通知日期时出现以下错误.

由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[valueForUndefinedKey:]:此类不是关键日期的密钥值编码兼容.

是否有一种方法可以同时支持新旧通知.

谢谢.

ios ios10 unnotificationrequest unusernotificationcenter

9
推荐指数
1
解决办法
1821
查看次数

使用UNUserNotificationCenter时,iOS 11崩溃并发生bundleProxy!= nil错误

以下代码行是我们的应用程序突然开始在iOS 11/11.0.1/11.0.2/11.1.1/11.2.2上针对某些用户崩溃的地方:

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
Run Code Online (Sandbox Code Playgroud)

我们有这个didFinishLaunchingWithOptions.崩溃报告说:

Fatal Exception: NSInternalInconsistencyException
Invalid parameter not satisfying: bundleProxy != nil

Fatal Exception: NSInternalInconsistencyException
0  CoreFoundation                 0x1869b3d38 __exceptionPreprocess
1  libobjc.A.dylib                0x185ec8528 objc_exception_throw
2  CoreFoundation                 0x1869b3c0c +[NSException raise:format:]
3  Foundation                     0x187342c24 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:]
4  UserNotifications              0x18fcc973c -[UNUserNotificationCenter initWithBundleProxy:]
5  UserNotifications              0x18fcc950c __53+[UNUserNotificationCenter currentNotificationCenter]_block_invoke
6  libdispatch.dylib              0x186339048 _dispatch_client_callout
7  libdispatch.dylib              0x18633c710 dispatch_once_f$VARIANT$mp
8  UserNotifications              0x18fcc94ac +[UNUserNotificationCenter currentNotificationCenter]
Run Code Online (Sandbox Code Playgroud)

它来自iOS清楚.还有其他人遇到同样的错误吗?知道发生了什么事吗?

crash objective-c unusernotificationcenter ios11

9
推荐指数
1
解决办法
1942
查看次数

如何对特定于区域设置的本地通知进行单元测试

我刚刚在我的应用中添加了本地通知。当应用区域设置regionCode(即Locale.current.regionCode)为“ US”或“ CA”时,才触发这些通知。我对语言环境感兴趣language

我还将要编写补充的测试用例,但是一旦我知道如何编写一个测试用例,其他的就自然而然地遵循了。

因此,我的问题是:如何将Locale注入测试中(请参阅参考资料testSuccessfulNotificationDelivery())?

LocalNotificationTests.swift

class LocalNotificationTests: XCTestCase {

    let notification1 = LocalNotification(toTriggerInSeconds: 5)
    let notification2 = LocalNotification(toTriggerInSeconds: 6)

    // This object manages LocalNotifications 
    // by building them into UNUserNotifications
    // and then scheduling them using UNUserNotificationCenter.
    let notificationManager = NotificationManager()

    func testSuccessfulNotificationDelivery() {

        // setup locale and use it for testing, somehow
        let  = Locale(identifier: "en_CA")

        // The answer to my question would …
Run Code Online (Sandbox Code Playgroud)

locale ios localnotification swift unusernotificationcenter

8
推荐指数
1
解决办法
311
查看次数

在ios10中添加自定义本地通知 - swift 3

我正在尝试添加自定义本地通知,但我只是通过我的操作获取股票通知:

在此输入图像描述

我的故事板看起来像这样(标准模板):

在此输入图像描述

我有一个UNNotificationExtensionCategory设置为awesomeNotification(在Info.plist中)的扩展名.此扩展的基础也是Notification Content来自的模板iOS - Application Extension.

在我的app委托中,我有这个:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    let center = UNUserNotificationCenter.current()

    let actions = [UNNotificationAction.init(identifier: "Hey", title: "Yo", options: UNNotificationActionOptions.foreground)]

    let category = UNNotificationCategory(identifier: "awesomeNotification", actions: actions, minimalActions: actions, intentIdentifiers: [], options: [])
    center.setNotificationCategories([category])

    center.requestAuthorization([.alert, .sound]) { (granted, error) in
    }

    return true
}
Run Code Online (Sandbox Code Playgroud)

在我的主应用程序的viewcontroller中,我有以下操作来触发它:

@IBAction func sendPressed(_ sender: AnyObject) {
    let content = UNMutableNotificationContent()

    content.categoryIdentifier = "awesomeNotification"
    content.title = …
Run Code Online (Sandbox Code Playgroud)

uilocalnotification swift swift3 ios10 unusernotificationcenter

7
推荐指数
1
解决办法
6581
查看次数

应用程序终止时未调用 UNUserNotificationCenter didReceive 响应

我正在处理本地通知,但我遇到的问题是当应用程序终止时没有调用 didReceive Response 方法,所以当我点击通知操作时,它只是启动应用程序而没有做任何其他事情。但是当应用程序只是在后台时,一切都像往常一样。我的代码有什么问题吗?

//MyClassNameViewController.swift

override func viewDidLoad() {
    super.viewDidLoad()

    UNUserNotificationCenter.current().delegate = self

}

func triggerAlarm1() {
    // Create an instance of notification center
    let center = UNUserNotificationCenter.current()

    // Sets the details of the notification
    let content = UNMutableNotificationContent()
    content.title = "Recorded Today's first alarm."
    content.body = "Be completely honest: how is your day so far?"
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "notificationID1"

    // Set the notification to trigger everyday
    let triggerDaily = Calendar.current.dateComponents([.hour,.minute], from: myTimePicker1.date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, …
Run Code Online (Sandbox Code Playgroud)

ios swift unusernotificationcenter

7
推荐指数
1
解决办法
6801
查看次数

用户通知请求始终带有默认操作标识符

我正在使用UNUserNotificationCenterDelegate(> ios 10)和其中一个委托方法,我可以检查来自通知的响应总是actionIdentifier等于"com.apple.UNNotificationDefaultActionIdentifier",无论我做什么."response.notification.request.content.categoryIdentifier"是正确的,具有预期值,但request.actionIdentifier永远不会正确(下面的示例中为"mycustomactionidentifier").有谁知道我错过了什么?

extension NotificationManager: UNUserNotificationCenterDelegate {


    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) {

        completionHandler([.alert,.sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) {

        if response.notification.request.content.categoryIdentifier == "TEST" {
            if response.actionIdentifier == "mycustomactionidentifier" {
                NSLog("it finally works dude!")
            }
        }

        completionHandler()
    }
}
Run Code Online (Sandbox Code Playgroud)

我将操作和类别添加到通知中心:

    let uploadAction = UNNotificationAction(identifier: "mycustomactionidentifier", title: "Uploaded", options: [])
    let category = UNNotificationCategory(identifier: "TEST", actions: [uploadAction], intentIdentifiers: [])
    center.setNotificationCategories([category])
Run Code Online (Sandbox Code Playgroud)

并发送请求正确的标识符:

    let uploadContent = …
Run Code Online (Sandbox Code Playgroud)

ios swift ios10 unusernotificationcenter

7
推荐指数
1
解决办法
4516
查看次数

Swift 中随机重复本地通知

TL;DR:是否可以在不使用APNS(或替代推送通知服务)的情况下获得重复的随机本地通知?

我正在构建一个Core Data包含一堆对象的应用程序。(我们将它们称为小部件。)每天的某个时间(假设是中午)我想发送一条通知以查看其中一个小部件。

didFinishLaunchingWithOptions我中检查以确保通知已启用并设置委托等,然后调用函数来构建本地通知。所有这一切都运行良好。

    var date = DateComponents()
    date.hour = 12
    date.minute = 00
    let content = UNMutableNotificationContent()
    content.title = "You should see this widget!"
    content.userInfo = ["widgetID": widget.id]
    content.body = "Today's Widget:\n\(widget.title!)"
    content.sound = UNNotificationSound.default()
    let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
    let request = UNNotificationRequest(identifier: notificationIdentifer, content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error : Error?) in if let theError = error { print(theError.localizedDescription)}}
Run Code Online (Sandbox Code Playgroud)

我的委托处理程序也正常工作:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse, …
Run Code Online (Sandbox Code Playgroud)

notifications apple-push-notifications swift unusernotificationcenter unnotificationtrigger

7
推荐指数
0
解决办法
1588
查看次数

即使函数体内没有任何内容, userNotificationCenter(_:didReceive:) 怎么会导致崩溃?

我有一个带有通知操作的应用程序。多年来,使用符合UNUserNotificationCenterDelegate其方法并处理其操作的类,一切都运行良好userNotificationCenter(_:didReceive:withCompletionHandler)

\n

最近,我重构了很多我的 app\xe2\x80\x99s 代码以使用 async/await。因此,我切换到委托方法的异步版本,userNotificationCenter(_:didReceive:) async它不再使用完成处理程序。

\n

在发布使用该方法的异步版本的更新后,我开始在我的设备上和野外看到大量崩溃。这里\xe2\x80\x99s 是一个示例,删除了应用程序名称:

\n
Exception Type:  EXC_CRASH (SIGABRT)\nException Codes: 0x0000000000000000, 0x0000000000000000\nTriggered by Thread:  16\n\nApplication Specific Information:\nabort() called\n\n\nLast Exception Backtrace:\n0   CoreFoundation                         0x197ba2248 __exceptionPreprocess + 164\n1   libobjc.A.dylib                        0x190f63a68 objc_exception_throw + 60\n2   Foundation                             0x19252281c _userInfoForFileAndLine + 0\n3   UIKitCore                              0x19aa4fe94 -[UIApplication _performBlockAfterCATransactionCommitSynchronizes:] + 404\n4   UIKitCore                              0x19aa5c20c -[UIApplication _updateStateRestorationArchiveForBackgroundEvent:saveState:exitIfCouldNotRestoreState:updateSnapshot:windowScene:] + 528\n5   UIKitCore                              0x19aa5c4d0 -[UIApplication _updateSnapshotAndStateRestorationWithAction:windowScene:] + 144\n6                                          0x1006c36a8 @objc closure #1 in NotificationDelegate.userNotificationCenter(_:didReceive:) + 132\n7                                          0x1006c37d1 partial apply for @objc closure #1 …
Run Code Online (Sandbox Code Playgroud)

ios unusernotificationcenter

6
推荐指数
1
解决办法
1294
查看次数