Anj*_*der 5 apple-push-notifications devicetoken ios swift
我试图获得 APNS 推送令牌。
func configPushNotifications(_ application: UIApplication) {
application.registerForRemoteNotifications()
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我使用的是 My Phone Sim Internet (4g/3g),则没有从 AppDelegate 收到任何令牌。
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
Run Code Online (Sandbox Code Playgroud)
但是如果我使用Wifi,它工作正常。我检查iOS 13.1.2和13.1.3。两者都有相同的问题。但较低的版本喜欢iOS 12 or 11工作正常。是苹果虫吗?或者我必须为移动网络请求具有不同配置的令牌?
请验证代码,如下所示
首先导入本地通知
import UserNotifications
Run Code Online (Sandbox Code Playgroud)
然后创建一个方法
func settingPushNotification() {
let app = UIApplication.shared
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
app.registerUserNotificationSettings(settings)
}
app.registerForRemoteNotifications()
}
Run Code Online (Sandbox Code Playgroud)
您可以以这种方式调用此appdelegate方法viewcontroller。
self.settingPushNotification()
Run Code Online (Sandbox Code Playgroud)
您需要添加委托方法
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
if !token.isEmpty {
let userDefaults = UserDefaults.standard
userDefaults.set(token, forKey: Strings.DeviceToken.rawValue)
}
print("Device Token: \(token)")
}
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register: \(error)")
}
Run Code Online (Sandbox Code Playgroud)
确保您在签名和功能中添加了推送通知。
这样您就可以获得 APNS 设备令牌。
| 归档时间: |
|
| 查看次数: |
4464 次 |
| 最近记录: |