简单警报和徽章上的 IOS 10.2 UserNotifications 问题

2024-02-29

在写这篇文章之前,我对 UserNotification 框架进行了大量研究,该框架在 IOS 10 中取代了 UILocalNotification。我还按照本教程学习了有关此新功能的所有内容:http://useyourloaf.com/blog/local-notifications-with-ios-10/ http://useyourloaf.com/blog/local-notifications-with-ios-10/.

今天,我在实现如此琐碎的通知时遇到了很多麻烦,而且由于这是最近的新功能,我找不到任何解决方案(尤其是在 Objective C 中)!我目前有 2 个不同的通知,其中一个Alert和一个徽章更新.

警报问题

在将我的手机从 IOS 10.1 更新到 10.2 之前,我对 Appdelegate 发出了警报,每当用户手动关闭应用程序时,该警报就会立即触发:

-(void)applicationWillTerminate:(UIApplication *)application {
        NSLog(@"applicationWillTerminate");

        // Notification terminate
        [self registerTerminateNotification];
}

// Notification Background terminate 
-(void) registerTerminateNotification {
    // the center
    UNUserNotificationCenter * notifCenter = [UNUserNotificationCenter currentNotificationCenter];

    // Content
    UNMutableNotificationContent *content = [UNMutableNotificationContent new];
    content.title = @"Stop";
    content.body = @"Application closed";
    content.sound = [UNNotificationSound defaultSound];
    // Trigger 
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];
    // Identifier
    NSString *identifier = @"LocalNotificationTerminate";
    // création de la requête
    UNNotificationRequest *terminateRequest = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
    // Ajout de la requête au center
    [notifCenter addNotificationRequest:terminateRequest withCompletionHandler:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Error %@: %@",identifier,error);
        }
    }];
}

在 iOS 10.2 之前,它运行得很好,当我手动关闭应用程序时,会出现警报。但是自从我更新到IOS 10.2后,没有任何原因显示任何内容,我没有改变任何东西,我也看不到缺少什么。

徽章问题

我还尝试(这次仅在 IOS 10.2 中)在我的应用程序图标上实现徽章,效果很好,直到我尝试将其删除。这是执行此操作的函数:

+(void) incrementBadgeIcon {
    // only increment if application is in background 
    if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground){

        NSLog(@"increment badge");

        // notif center 
        UNUserNotificationCenter *notifCenter = [UNUserNotificationCenter currentNotificationCenter];

        // Content
        UNMutableNotificationContent *content = [UNMutableNotificationContent new];
        content.badge = [NSNumber numberWithInt:1];
        // Trigger 
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO];
        // Identifier
        NSString *identifier = @"LocalNotificationIncrementBadge";
        // request
        UNNotificationRequest *incrementBadgeRequest = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
        // Ajout de la requête au center
        [notifCenter addNotificationRequest:incrementBadgeRequest withCompletionHandler:^(NSError * _Nullable error) {
            if (error != nil) {
                NSLog(@"Error %@: %@",identifier,error);
            }
        }];
    }
}

目前,它不会增加徽章编号,正如其名称所暗示的那样,但它只是将徽章编号设置为 1。文档说,如果您设置内容.徽章到 0,它会删除它,但这不起作用。我尝试使用其他数字,当我手动将其更改为“2”、“3”等时...它会发生变化,但如果我将其设置为 0,则它不起作用。

另外,在我之前链接的教程中,提到了几个函数:getPendingNotificationRequests:completionHandler: and getDeliveredNotificationRequests:completionHandler:。我注意到,当我在调用后立即调用这些函数时增量徽章图标,如果 content.badge 设置为“1”、“2”等...它将出现在待处理通知列表中。但是,当我将其设置为 0 时,它不会出现在任何地方。我没有收到任何错误,Xcode 中也没有警告,并且我的应用程序徽章仍然存在。

有谁知道如何修复这两个警报?

预先感谢

PS:我也尝试过使用删除所有待处理通知请求 and 删除所有已发送通知两者都没有成功。


关于警报:

当本地通知触发时,您的应用程序可能仍处于前台,因此您需要实现委托方法才能使通知执行任何操作。例如,在委托中定义此方法将允许通知显示警报、发出声音并更新徽章:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert,.badge,.sound])
}

关于徽章:

我观察到创建一个UNMutableNotificationContent对象并仅指定徽章值(作为 NSNumber 对象)适用于除 0 之外的所有徽章值(即,您无法以这种方式清除徽章)。我还没有找到任何文档来解释为什么 0 的行为与任何其他值不同,特别是因为 .badge 属性被定义为NSNumber?,所以框架应该能够区分nil(没有变化)和0(清除徽章)。

我已经提交了一份radar http://www.openradar.me/29859960反对这一点。

作为解决方法,我发现设置title财产在UNMutableNotificationContent对象,其徽章值为NSNumber(value: 0) does火。如果title财产丢失,它不会着火。

添加 title 属性仍然不会向用户发出警报(更新:iOS 11 中不再出现这种情况!),所以这是一种静默地将徽章值更新为 0 的方法,无需调用 UIApplication 对象(通过UIApplication.shared.applicationIconBadgeNumber = 0).

这是我的示例项目中的全部代码; ViewController 代码中有一个标记,显示插入 title 属性可以解决问题:

//
//  AppDelegate.swift
//  userNotificationZeroBadgeTest
//
//  Created by Jeff Vautin on 1/3/17.
//  Copyright © 2017 Jeff Vautin. All rights reserved.
//

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert, .sound]) { (success, error) -> Void in
            print("Badge auth: \(success)")
        }

        // For handling Foreground notifications, this needs to be assigned before finishing this method
        let vc = window?.rootViewController as! ViewController
        let center = UNUserNotificationCenter.current()
        center.delegate = vc

        return true
    }
}

//
//  ViewController.swift
//  userNotificationZeroBadgeTest
//
//  Created by Jeff Vautin on 1/3/17.
//  Copyright © 2017 Jeff Vautin. All rights reserved.
//

import UIKit
import UserNotifications

class ViewController: UIViewController, UNUserNotificationCenterDelegate {

    @IBAction func start(_ sender: Any) {
        // Reset badge directly (this always works)
        UIApplication.shared.applicationIconBadgeNumber = 0


        let center = UNUserNotificationCenter.current()

        // Schedule badge value of 1 in 5 seconds
        let notificationBadgeOneContent = UNMutableNotificationContent()
        notificationBadgeOneContent.badge = NSNumber(value: 1)
        let notificationBadgeOneTrigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 1*5, repeats: false)
        let notificationBadgeOneRequest = UNNotificationRequest.init(identifier: "1", content: notificationBadgeOneContent, trigger: notificationBadgeOneTrigger)
        center.add(notificationBadgeOneRequest)

        // Schedule badge value of 2 in 10 seconds
        let notificationBadgeTwoContent = UNMutableNotificationContent()
        notificationBadgeTwoContent.badge = NSNumber(value: 2)
        let notificationBadgeTwoTrigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 2*5, repeats: false)
        let notificationBadgeTwoRequest = UNNotificationRequest.init(identifier: "2", content: notificationBadgeTwoContent, trigger: notificationBadgeTwoTrigger)
        center.add(notificationBadgeTwoRequest)

        // Schedule badge value of 3 in 15 seconds
        let notificationBadgeThreeContent = UNMutableNotificationContent()
        notificationBadgeThreeContent.badge = NSNumber(value: 3)
        let notificationBadgeThreeTrigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 3*5, repeats: false)
        let notificationBadgeThreeRequest = UNNotificationRequest.init(identifier: "3", content: notificationBadgeThreeContent, trigger: notificationBadgeThreeTrigger)
        center.add(notificationBadgeThreeRequest)

        // Schedule badge value of 4 in 20 seconds
        let notificationBadgeFourContent = UNMutableNotificationContent()
        notificationBadgeFourContent.badge = NSNumber(value: 4)
        let notificationBadgeFourTrigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 4*5, repeats: false)
        let notificationBadgeFourRequest = UNNotificationRequest.init(identifier: "4", content: notificationBadgeFourContent, trigger: notificationBadgeFourTrigger)
        center.add(notificationBadgeFourRequest)

        // Schedule badge value of 0 in 25 seconds
        let notificationBadgeZeroContent = UNMutableNotificationContent()
        // MARK: Uncommenting this line setting title property will cause notification to fire properly.
        //notificationBadgeZeroContent.title = "Zero!"
        notificationBadgeZeroContent.badge = NSNumber(value: 0)
        let notificationBadgeZeroTrigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5*5, repeats: false)
        let notificationBadgeZeroRequest = UNNotificationRequest.init(identifier: "0", content: notificationBadgeZeroContent, trigger: notificationBadgeZeroTrigger)
        center.add(notificationBadgeZeroRequest)
    }

    @IBAction func listNotifications(_ sender: Any) {
        let center = UNUserNotificationCenter.current()
        center.getDeliveredNotifications() { (notificationArray) -> Void in
            print("Delivered notifications: \(notificationArray)")
        }
        center.getPendingNotificationRequests() { (notificationArray) -> Void in
            print("Pending notifications: \(notificationArray)")
        }
    }

    // MARK: UNUserNotificationCenterDelegate

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("Received notification: \(notification)")
        completionHandler([.alert,.badge,.sound])
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

简单警报和徽章上的 IOS 10.2 UserNotifications 问题 的相关文章

  • 如何呈现半屏模态视图?

    我有一个 UIViewController 当按下按钮时 我想要一个半屏视图向上滑动 其中有一个 UIPicker 我在 IB 中使用 UIPicker 和带有 完成 取消 按钮的 UIToolBar 制作了一个 UIView 我怎样才能做
  • 使用可达性有什么好处?

    与下面的代码相比 使用 Reachability 有什么优势 我觉得 Reachability 有大量代码 但如果它在任何方面更好 那么我会使用它 NSString connectionString NSString alloc initW
  • WKWebView不加载https URL?

    我有一个 WKWebView 应该加载以下网址 https buchung salonmeister de place offer details page id 907599 venueId 301655 她是我使用的代码 import
  • 创建电子书阅读应用程序的教程 - epub 文件格式 [重复]

    这个问题在这里已经有答案了 我正在制作一个电子书阅读应用程序 因为我想执行一些操作 例如更改文本颜色 字体 选择文本等 我知道 iphone os 4 0 和 ipad 现在支持 epub 文件格式 但我不知道如何创建此类应用程序 如果有人
  • 应用内购买:卡在 paymentWithProductIdentifiers - 已弃用

    我一直在设置应用内购买 我无法做到这一点 SKPayment paymentRequest SKPayment paymentWithProduct co za nideo 100shotsbuybeer 我从 SKPayment paym
  • Firebase queryOrderedbyChild 不返回 Null 值

    我有一个根据年龄搜索用户的查询 self ref child users queryOrdered byChild age queryStarting atValue 18 queryEnding atValue 25 observeSin
  • 如何将动画应用到 GMSMarker

    我正在通过使用适用于 iOS V1 1 0 的 Google Maps SDK 将 iOS 地图迁移到 google 地图来更改我的应用程序 并且我尝试在添加 删除时对标记进行动画处理 但我在与此相关的文档中没有找到任何建议 请建议我如何在
  • UITableViewCell 上的自动布局问题

    我在使用自动布局时遇到问题xcode 5项目 我在内部使用带有导航控制器的普通视图控制器 我有一个MKMapView在上半部分和一个UITableView在下半部分 我在用storyboards 并配置了原型UITableViewCell
  • 更改 UIImageView 的位置

    我怎样才能为 UIImageView 做一个简单的位置改变 假设当前坐标是 x 20 和 y 30 我想将其移至 x 100 和 y 100 可以制作运动动画吗 你需要改变它的CGFrameUIImageView就像这样 imageView
  • 如何获取原始触摸屏数据?

    我知道我可以在 iPhone 应用程序中获取触摸事件 但这些触摸事件都被我过滤掉了 如果我将设备按在脸上 它会过滤掉这些触摸事件 因为它可以检测到它不是手指 我如何获得原始触摸事件 而不以任何方式过滤 没有用于此目的的公共 API 您可以获
  • 将 NSString 分离成 N​​SArray,但允许用引号对单词进行分组

    我有一个搜索字符串 人们可以使用引号将短语组合在一起 并将其与单个关键字混合 例如 像这样的字符串 Something amazing rooster 我想把它分成一个 NSArray 这样它就有Something amazing 不带引号
  • 将更新的图像保存到 PhotoKit 时缺少图像元数据

    我在更新图像的元数据并将其保存回照片库时遇到问题 一切works除了更改后的图像元数据丢失了之前存在的条目 并且我在操作图像或执行照片库更改块时没有收到任何错误 另外 在写回图像之前的字典看起来就像原始字典加上我在调试器中的字典 我的问题是
  • CLGeocoder reverseGeocodeLocation 返回“kCLErrorDomain 错误 9”

    我正在根据本文开发具有反向地理编码功能的 iOS 应用程序 地理编码教程 http jonathanfield me jons blog clgeocoder example html 但是当我在模拟器上进行这样的测试时 我收到 kCLEr
  • Phonegap - navigator.app.backHistory() 不适用于 HTML 后退按钮

    在我的应用程序中 我使用phonegap 2 6 对于后退按钮 我使用以下函数 document addEventListener backbutton onBackKeyDown false function onBackKeyDown
  • CoreBluetooth广告检测时间

    这个问题早在10月份就已经讨论过here https stackoverflow com questions 12866551 corebluetooth connection setup time varies quite a bit 1
  • 反应本机套接字 io 没有从客户端发出事件

    尝试将socket io client与react native 现在是ios 一起使用 到目前为止 连接 从客户端接收服务器端事件似乎工作正常 但是我似乎无法从客户端发出任何事件 Client var socket io http loc
  • iOS UIView子类,将透明文本绘制到背景

    我想将文本绘制到 UIView 上的子类上 以便文本从形状中切出 并且视图后面的背景显示出来 就像在 OSX Mavericks 徽标中找到的那样here http www n3rdabl3 co uk wp content uploads
  • Xcode 6.1“Xcode 调试器中内置的 Swift REPL 可以检查和操作正在运行的应用程序”不起作用

    对于 Xcode 6 1 更新点之一是 Xcode 调试器内置的 Swift REPL 可以检查和操作 你的跑步应用程序 我创建了空项目 在 viewDidLoad 中设置了一个断点 当应用程序在断点处停止时 我在 Xcode 控制台中输入
  • 如何在 iPhone 应用程序中使用正则表达式以 , (逗号)分隔字符串

    我必须读取包含三列的 csv 文件 在解析 csv 文件时 我得到了这种格式的字符串克里斯托弗 巴斯 为心爱的国家哭泣 期末论文 电子邮件受保护 cdn cgi l email protection 我想将三列的值存储在一个数组中 所以我使
  • 如何检查 iOS 分发配置文件是否启用了推送通知?

    我有一个应用程序应该启用推送通知 但由于某种原因没有启用它们 我见过其他人下载并安装了该应用程序 但它甚至没有提示他们授予发送推送通知的权限 正如预期的那样 此应用程序不会出现在其 设置 gt 通知 中 但是 在我的 iPad 上 我能够从

随机推荐

  • 在另一个指令内渲染指令(在转发器模板内)

    我试图在另一个指令中渲染一个指令 不确定模板内的转发器是否正在工作 它似乎只是作为文本输出而不是编译该指令 此处的plunker代码 http plnkr co edit IRsNK9 http plnkr co edit IRsNK9 关
  • 有没有办法用异或翻转32位浮点数的符号位?

    我正在尝试翻转 xmm0 内部最低有效浮点数的符号位 我尝试将 0 转换为另一个 xmm 寄存器 并将其与 xmm0 进行异或 不幸的是 尽管我的浮动值已经消失 但我已经实现了翻转标志 有没有办法使用xorps在asm中为了翻转符号位 我还
  • 独立 Jython:导入错误 (Apache-POI)

    当我尝试将 Jython 与 Apache POI 一起使用时 Jython 独立 jar 抛出 ImportError 异常 您将在下面找到我如何调用 Jython 脚本 java cp C jAutoMailerScript lib p
  • 类作用域变量与方法作用域变量

    我知道变量范围是由块的开头包围的 和块的末尾 如果在块内声明相同的变量 则编译错误Variable already defined发生 但看看下面的例子 public class Test int x 0 Class scope varia
  • 三元运算符(内联如果没有其他)

    我有两个checkbox in a
  • java xml document.getTextContent() 保持为空

    我正在尝试在 JUnit 测试中构建 xml 文档 doc docBuilder newDocument Element root doc createElement Settings doc appendChild root Elemen
  • 如何使用 MVC Html Helpers 截断字符串?

    我正在尝试截断一个长字符串 以便仅在我的索引页上显示 它显示如下 td Html DisplayFor modelItem gt item Description td 描述可以有 500 个字符长 但我无法在网格布局上显示那么多 我想只显
  • 如何增加 tinter 列表框中行之间的间距 - python

    我有一个 tkinter 列表框初始化如下 self serives listbox tk Listbox parent font TkTextFont 20 exportselection False width 30 height 15
  • 捕获视频文件的输出以进行逐帧处理

    我试图从视频文件 7 秒长 中抓取各个帧 但遇到了巨大的内存问题 我正在使用 AVURLAsset 加载资产 然后创建一个AVAssetReader以及随附的AVAssetReaderTrackOutput 采用像素格式kCVPixelFo
  • 使用 KSoap 库使用 .NET Web 服务时出现错误

    我一直在使用 ksoap 库来使用 net Web 服务 我遇到了这种错误 预计 START TAG http schemas xmlsoap org soap envelope http schemas xmlsoap org soap
  • 在 OpenGL ES 2.0 / GLSL 中,哪里需要精度说明符?

    您要填充值的变量是否决定了您在等号右侧使用的精度 例如 这里的精度说明符在含义上是否有任何区别 gl FragColor lowp vec4 1 这是另一个例子 lowp float floaty 1 2 floaty lowp 1 low
  • Bash 监控磁盘使用情况

    我买了一个 NAS 盒子 上面有 debian 的精简版 前几天它空间不足 但我没有意识到 我基本上想编写一个 bash 脚本 每当磁盘已满 90 以上时就会提醒我 有谁知道可以执行此操作的脚本或给我一些关于编写脚本的建议吗 bin bas
  • C# 获取 cmd 输出,如真实 cmd 窗口中所示

    我有一个BackgroundWorker运行 cmd 进程并向其写入多个命令的线程 有些命令可能需要一段时间才能完成 因此我想向用户显示进度的 cmd 输出 我运行 cmd 命令的代码如下所示 private void background
  • 在C中的两点之间选取随机数

    我想知道 是否有可能在 c 中生成两个限制之间的随机数 IE 我的程序是这样设置的 function x generate random number while 1 function x delay 所以基本上我希望每次调用该函数时都会生
  • 何时在基准测试表达式中进行插值

    The 基准测试工具文档建议将全局变量插入基准测试表达式中 然而 他们提供的示例的运行时间差距似乎已经大大缩小 在他们的例子 https github com JuliaCI BenchmarkTools jl blob master do
  • 带有上下文管理器的 ThreadPoolExecutor

    我不明白为什么这段代码的行为方式不同 在第一种情况下 代码将打印 elo 19 秒后我们将看到 3 在其他情况下 我们将首先等待 19 秒 然后我们将看到 elo 你能给我解释一下吗 from concurrent futures impo
  • 斐波那契计算时间

    递归式斐波那契与循环式斐波那契之间是否存在明显的计算时间差异 我使用递归将斐波那契数列运行到 40 个位置 然后直接使用循环 看起来计算时间的差异只是academic 用C语言编写 递归解决方案 int main int argc cons
  • 如何在启动过程后切换Linux内核控制台?

    在我的嵌入式系统上 我通常使用 dev ttyS0 作 为主控制台 这是通过传递内核参数来实现的console dev ttyS0什么时候init尽其所能 getty在指定的同一设备上触发inittab by eg ttyS0 respaw
  • 将毫秒时间戳反序列化为 java.time.Instant

    我正在尝试使用 Jackson 读取 JSON 文件并将以纪元毫秒形式存储的字段之一存储为 JavaInstant 但是反序列化的行为并不如预期 这是我在尝试读取时间戳时看到的内容 1503115200000 杰克逊正在设定Instant字
  • 简单警报和徽章上的 IOS 10.2 UserNotifications 问题

    在写这篇文章之前 我对 UserNotification 框架进行了大量研究 该框架在 IOS 10 中取代了 UILocalNotification 我还按照本教程学习了有关此新功能的所有内容 http useyourloaf com b