示例代码:
在Xcode中找到项目的Targets,然后选择Capabilities选项。找到Push Notifications并打开它。确保Push Notifications功能已启用,并且正确的证书已选择。如果需要,使用更新的证书和私钥重新创建证书。
//示例代码 import UIKit import UserNotifications
@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//请求用户授权推送通知
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
//用户允许授权
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
} else {
//用户不允许授权
print("User did not grant permission for push notifications")
}
}
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
//将设备的push token发送给服务器进行注册
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
//注册push token失败,打印错误信息
print("Failed to register for remote notifications with error: \(error.localizedDescription)")
}
//接收到推送通知的回调方法
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//处理接收到的推送通知
}
}