#swift #azure #apple-push-notifications #swift3
#swift #azure #apple-push-уведомления #swift3
Вопрос:
После обновления моего приложения до Swift 3 (какой это был опыт! ) — Я знал, что мне пришлось переработать код уведомления из-за изменений в iOS10.
Используя этот полезный ресурс — я смог перекодировать, и я получаю действительное соединение
Я также внес изменения в возможности проекта, добавив 1) Уведомления и 2) Фоновые режимы / удаленные уведомления.
Однако, когда я отправляю тестовое сообщение через функцию Azure «тестовая отправка», я его не получаю.
Вот соответствующий код из моего AppDelegate:
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Register for remote notifications
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
UIApplication.shared.registerForRemoteNotifications()
}
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let hub: SBNotificationHub = SBNotificationHub.init(connectionString: APISettings.Instance.notificationHubEndpoint, notificationHubPath: APISettings.Instance.notificationHubName)
hub.registerNative(withDeviceToken: deviceToken, tags: nil) { (error) -> Void in
if (error != nil){
print("Error registering for notifications: %@", error)
} else {
print("Registration ok")
}
}
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
print("Error = ",error.localizedDescription)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
print(userInfo)
}
// MARK: UNUserNotificationCenter Delegate // >= iOS 10
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("User Info = ",notification.request.content.userInfo)
completionHandler([.alert, .badge, .sound])
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("User Info = ",response.notification.request.content.userInfo)
completionHandler()
}
Буду признателен за любую помощь.
Комментарии:
1. Вы включили доступ к связке ключей в «Возможности»?
2. Спасибо за ответ — да, связка ключей включена
3. Можете ли вы попробовать установить приоритет push-уведомления, отправляемого из azure, на высокий
Ответ №1:
Попробуйте вызвать эту функцию в didFinishLaunchingWithOptions и очистить > Запустить ваше приложение
функция registerNotification()
{
UIApplication.sharedApplication() пусть application = UIApplication.sharedApplication()
если application.responsestoselector(#selector(UIApplication.registerUserNotificationSettings(_:)))
{
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
}
функциональное приложение (application: UIApplication, зарегистрировало настройки уведомлений пользователя: UIUserNotificationSettings) {
if notificationSettings.types != .None {
application.registerForRemoteNotifications()
}
}
Комментарии:
1. Я не вижу, как это пытается решить проблему. Пожалуйста, уточните.