Подтвердить что ты не робот

UILocalNotification устарела в iOS10

Это может быть вопрос заранее, но мне интересно, что использовать вместо UILocalNotification в iOS10. Я работаю над приложением, которое имеет цель развертывания iOS8, так что будет нормально использовать UILocalNotification?

4b9b3361

Ответ 1

Да, вы можете использовать UILocalNotification, старые API также отлично работают с iOS10, но вместо этого нам лучше использовать API в структуре пользовательских уведомлений. Есть также некоторые новые функции, вы можете использовать только с iOS10 User Notifications.

Это также случается с удаленным уведомлением, для получения дополнительной информации: здесь.

Новые возможности:

  1. Теперь вы можете либо представить оповещение, звук или увеличить значок, в то время как приложение находится на переднем плане тоже с iOS 10
  2. Теперь вы можете обрабатывать все события в одном месте, когда пользователь нажал (или сдвинул) кнопку действия, даже когда приложение уже было убито.
  3. Поддержка 3D-касания вместо раздвижного жестов.
  4. Теперь вы можете удалить специфическое локальное уведомление только одним кодом строки.
  5. Поддержка Rich Notification с пользовательским интерфейсом.

Нам очень легко преобразовать API UILocalNotification API-интерфейсы iOS10 User Notifications, они действительно похожи.

Я пишу демо здесь, чтобы показать, как использовать новые и старые API одновременно: iOS10AdaptationTips.

Например,

С реализацией Swift:

  1. import UserNotifications

    ///    Notification become independent from UIKit
    import UserNotifications
    
  2. запросить авторизацию для localNotification

        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
    
  3. расписание localNotification

  4. обновить значок значка значка приложения

    @IBAction  func triggerNotification(){
        let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: "Elon said:", arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: "Hello Tom!Get up, let play with Jerry!", arguments: nil)
        content.sound = UNNotificationSound.default()
        content.badge = UIApplication.shared().applicationIconBadgeNumber + 1;
        content.categoryIdentifier = "com.elonchan.localNotification"
        // Deliver the notification in 60 seconds.
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0, repeats: true)
        let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
    
        // Schedule the notification.
        let center = UNUserNotificationCenter.current()
        center.add(request)
    }
    
    @IBAction func stopNotification(_ sender: AnyObject) {
        let center = UNUserNotificationCenter.current()
        center.removeAllPendingNotificationRequests()
        // or you can remove specifical notification:
        // center.removePendingNotificationRequests(withIdentifiers: ["FiveSecond"])
    }
    

Реализация Objective-C:

  1. import UserNotifications

    // Notifications are independent from UIKit
    #import <UserNotifications/UserNotifications.h>
    
  2. запросить авторизацию для localNotification

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!error) {
                                  NSLog(@"request authorization succeeded!");
                                  [self showAlert];
                              }
                          }];
    
  3. расписание localNotification

  4. обновить значок значка значка приложения

    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:"
                                                        arguments:nil];
    content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let play with Jerry!"
                                                       arguments:nil];
    content.sound = [UNNotificationSound defaultSound];
    
    // 4. update application icon badge number
    content.badge = [NSNumber numberWithInteger:([UIApplication sharedApplication].applicationIconBadgeNumber + 1)];
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                triggerWithTimeInterval:5.f
                                                repeats:NO];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                        content:content
                                                                        trigger:trigger];
    /// 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@"add NotificationRequest succeeded!");
        }
    }];
    

Перейдите сюда для получения дополнительной информации: iOS10AdaptationTips.

обновленный

Завершение приложения из-за неперехваченного исключения "NSInternalInconsistencyException", причина: "интервал времени должен быть не менее 60, если повторяется"

let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60, repeats: true)

Ответ 2

Apple сделала это снова, правильная реализация: AppDelegate.swift

if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.currentNotificationCenter()
        center.requestAuthorizationWithOptions([.Alert, .Sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
    } else {
        // Fallback on earlier versions
    }

и не забудьте добавить

import UserNotifications

Ответ 3

Локальные уведомления для iOS 10 в Objetcive-C

Если вы программируете какое-то время, я уверен, что вы знакомы с классом UILocalNotification, и прямо сейчас с прибытием iOS 10 вы можете видеть, что UILocalNotification устарел. Для подробной реализации посетите этот пост в блоге

https://medium.com/@jamesrochabrun/local-notifications-are-a-great-way-to-send-notifications-to-the-user-without-the-necessity-of-an-b3187e7176a3#.nxdsf6h2h

Ответ 4

быстрый 4

if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .badge, .sound])  { (granted, error) in
            // Enable or disable features based on authorization.
        }
    } else {
        // REGISTER FOR PUSH NOTIFICATIONS
        let notifTypes:UIUserNotificationType  = [.alert, .badge, .sound]
        let settings = UIUserNotificationSettings(types: notifTypes, categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
        application.applicationIconBadgeNumber = 0

    }

MARK: - ДЕЛЕГАТЫ ДЛЯ УВЕДОМЛЕНИЯ ПУШКИ

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let installation = PFInstallation.current()
    installation?.setDeviceTokenFrom(deviceToken)
    installation?.saveInBackground(block: { (succ, error) in
        if error == nil {
            print("DEVICE TOKEN REGISTERED!")
        } else {
            print("\(error!.localizedDescription)")
        }
    })
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print("\(userInfo)")

    // PFPush.handle(userInfo)
    if application.applicationState == .inactive {
        PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(inBackground: userInfo, block: nil)
    }
}