首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在ios 10中为不同的本地通知启动不同的视图控制器

在iOS 10中,可以通过设置不同的category和identifier来为不同的本地通知启动不同的视图控制器。

首先,在AppDelegate中注册通知的category和action,可以通过UNUserNotificationCenter来实现:

代码语言:txt
复制
import UserNotifications

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // 注册通知的category和action
    let center = UNUserNotificationCenter.current()
    center.delegate = self
    
    let category = UNNotificationCategory(identifier: "CategoryIdentifier", actions: [], intentIdentifiers: [], options: [])
    center.setNotificationCategories([category])
    
    return true
}

然后,在AppDelegate中实现UNUserNotificationCenterDelegate的方法,处理通知的点击事件:

代码语言:txt
复制
extension AppDelegate: UNUserNotificationCenterDelegate {
    // 当用户点击通知时调用
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // 获取通知的category和identifier
        let category = response.notification.request.content.categoryIdentifier
        let identifier = response.notification.request.identifier
        
        if category == "CategoryIdentifier" {
            if identifier == "Notification1" {
                // 启动对应的视图控制器
                let viewController1 = ViewController1()
                // 设置为根视图控制器
                window?.rootViewController = viewController1
            } else if identifier == "Notification2" {
                let viewController2 = ViewController2()
                window?.rootViewController = viewController2
            }
        }
        
        completionHandler()
    }
}

接下来,在发送本地通知时,设置对应的category和identifier:

代码语言:txt
复制
import UserNotifications

func scheduleNotification() {
    let center = UNUserNotificationCenter.current()
    
    let content = UNMutableNotificationContent()
    content.title = "Notification Title"
    content.body = "Notification Body"
    content.categoryIdentifier = "CategoryIdentifier"
    content.sound = UNNotificationSound.default
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
    let request = UNNotificationRequest(identifier: "Notification1", content: content, trigger: trigger)
    
    center.add(request) { (error) in
        if let error = error {
            print("Error scheduling notification: \(error.localizedDescription)")
        }
    }
}

以上代码中,通过设置不同的identifier来区分不同的本地通知,并在AppDelegate的代理方法中根据identifier来启动对应的视图控制器。注意,这里只是示例代码,实际应用中需要根据具体需求进行调整。

推荐的腾讯云相关产品:腾讯移动推送(https://cloud.tencent.com/product/tpns)

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券