在没有Storyboard的情况下,可以通过编程方式实现在点击通知时访问特定的ViewController。以下是一种实现方式:
import UserNotifications
class NotificationHandler: NSObject, UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// 获取通知的标识符
let identifier = response.notification.request.identifier
// 根据标识符判断需要打开的ViewController
if identifier == "NotificationIdentifier" {
let viewController = SpecificViewController()
// 在这里可以进行一些其他的处理,例如传递参数等
// 获取当前的window
guard let window = UIApplication.shared.windows.first else {
return
}
// 设置ViewController为rootViewController
window.rootViewController = viewController
window.makeKeyAndVisible()
}
// 完成处理
completionHandler()
}
}
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let notificationHandler = NotificationHandler()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 注册通知处理类
UNUserNotificationCenter.current().delegate = notificationHandler
// 请求用户授权通知
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
// 处理授权结果
}
// 其他初始化操作
return true
}
// 其他AppDelegate方法
}
import UserNotifications
func sendNotification() {
let content = UNMutableNotificationContent()
content.title = "通知标题"
content.body = "通知内容"
content.sound = UNNotificationSound.default
content.badge = 1
// 设置通知的identifier为特定的值
let request = UNNotificationRequest(identifier: "NotificationIdentifier", content: content, trigger: nil)
// 发送通知
UNUserNotificationCenter.current().add(request) { (error) in
// 处理发送结果
}
}
以上代码示例中,通过自定义的通知处理类,在点击通知时判断通知的标识符,如果是特定的值,则创建并设置特定的ViewController为rootViewController,从而实现在点击通知时访问特定的ViewController。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云