iOS开发新手求助:获取Device Token时遇代码报错问题
解决AppDelegate找不到
configureUserInteractions()方法的问题 嘿,作为iOS新手碰到这个问题太正常啦!我来给你捋清楚为啥会报错,以及怎么解决:
报错原因
苹果文档里的configureUserInteractions()是示例代码中自定义的方法,不是iOS系统SDK自带的API!也就是说,文档里的这个方法是苹果用来演示如何封装通知交互逻辑的,你自己的AppDelegate里没写这个方法,编译器肯定会报“没有这个成员”的错误。
两种解决思路
1. 自己实现这个自定义方法
如果你需要处理通知相关的用户交互(比如请求通知权限、设置通知展示规则),可以在AppDelegate里添加这个方法,把你需要的逻辑写进去。举个最常用的例子——用来请求通知权限并注册远程通知:
func configureUserInteractions() { // 设置通知中心代理,方便处理前台通知等逻辑 UNUserNotificationCenter.current().delegate = self // 请求通知权限 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if let error = error { print("请求通知权限出错:\(error.localizedDescription)") return } // 权限获取成功后,注册远程通知 if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } }
2. 暂时跳过这个方法,先跑通Device Token核心流程
如果你暂时不需要封装交互逻辑,也可以直接把调用self.configureUserInteractions()的代码注释掉,先把获取Device Token的核心流程写好:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 直接在这里写请求权限和注册远程通知的逻辑 UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in if granted { DispatchQueue.main.async { application.registerForRemoteNotifications() } } } return true } // 获取Device Token的核心方法 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // 把Data类型的Token转成字符串格式 let tokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() print("拿到Device Token啦:\(tokenString)") // 这里可以把Token发送到你的后端服务器 } // 注册失败的回调 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("注册远程通知失败:\(error.localizedDescription)") } // 扩展实现通知代理,处理前台通知展示 extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 前台收到通知时,展示弹窗和声音 completionHandler([.alert, .sound]) } }
最后提醒
记得在Xcode的项目配置里开启“Push Notifications”能力(在Signing & Capabilities里添加),不然注册远程通知会失败哦!
内容的提问来源于stack exchange,提问作者xyzcode




