King-wit 2019-01-24 16:50 采纳率: 0%
浏览 236

iOS 测试 求助,关于如何读取并收集 iOS 通知消息的问题

需求:
1、需要测试 APP 的离线推送消息,统计每次APP收到离线推送消息的时间,比如服务器给某个 APP 推送100条通知消息
现在需要统计 APP 收到离线推送消息的次数,并记录收到通知消息的时间

2、如何使用现有工具满足这一需求(离线推送消息不能打开该被测试 APP 的进程)

请问题一下各位谁有好的方法方案尼,目前我是使用了 appium 测试,但是这个方法有很多局限性,不好使用

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-07 19:15
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    要实现您描述的功能,您可以利用iOS的Core Messaging框架来接收和处理离线推送通知。以下是一些步骤和可能的方法:

    1. 安装依赖库:首先确保您的项目中已安装了CocoaPods或者Carthage来管理第三方库。

    2. 设置通知权限:检查是否有足够的权限来获取用户的通知权限。如果用户不同意,那么他们将无法接收到任何通知。

    3. 监听通知:使用Core Messaging API监听来自服务器的消息。这可以通过在您的应用程序的启动时调用NSNotificationCenter.defaultCenter.addObserver(_:name:object:)来完成,其中object是一个CMNotification对象,表示一个新的通知。

    4. 计数器:在Core Messaging API中,可以创建一个计数器来跟踪收到的所有通知数量。当一个通知被添加到队列时,它会被添加到计数器中。例如:

    let notificationCount = NSNotificationCenter.defaultCenter.addObserver(forName: "com.example.notification", object: nil, queue: nil) { _ in
        // 更新通知计数器
    }
    
    1. 时间戳:为了记录每个通知发送的时间,您可以使用NSDateFormatter来格式化日期。例如,在addObserver(_:name:object:)回调中,你可以这样做:
    func addNotificationObserver() {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        NSNotificationCenter.defaultCenter.addObserver(self, selector: #selector(updateNotificationTimestamp), name: "com.example.notification", object: nil)
    }
    
    @objc func updateNotificationTimestamp(_ sender: Any) {
        let timestamp = Date().timeIntervalSince1970
        print("Received notification at \(timestamp)")
    }
    
    1. 定时更新:为了定期更新通知计数器,可以考虑每隔一段时间就调用updateNotificationCounter()函数。
    2. 数据收集:最后,您可以在后台程序中使用NSLog打印出通知的数量和发送时间,以查看是否符合预期的效果。

    完整的示例代码如下:

    import CoreMessaging
    
    class NotificationHandler: NSObject, CMNotificationDelegate {
        var notificationCount: Int = 0
        
        func updateNotificationCounter() {
            self.notificationCount += 1
        }
        
        func addNotificationObserver() {
            let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            
            NSNotificationCenter.defaultCenter.addObserver(self, selector: #selector(updateNotificationTimestamp), name: "com.example.notification", object: nil)
        }
        
        @objc func updateNotificationTimestamp(_ sender: Any) {
            let timestamp = Date().timeIntervalSince1970
            print("Received notification at \(timestamp)")
            updateNotificationCounter()
        }
        
        func applicationDidFinishLaunching(_ aNotification: Notification) {
            addNotificationObserver()
        }
    }
    

    请注意,上述代码仅为示例,实际应用中还需要根据具体的需求进行调整和优化。

    评论

报告相同问题?