2017-02-09 20 views
6

Как настроить приложение AppDelegate для обработки push-уведомлений, возникающих, когда приложение находится на переднем плане и в фоновом режиме с быстрыми 3 и ios 10? В том числе, как заставить телефон вибрировать на переднем плане, если я получу уведомление.Как обрабатывать уведомления ios push, когда приложение находится на переднем плане?

ответ

7

Вот как я настроил свой AppDelegate файл, чтобы сделать это:

Для обработки уведомления толчка, импортировать следующую структуру:

import UserNotifications 

Чтобы сделать телефон вибрировал на импортируемые устройства следующие рамки :

import AudioToolbox 

Сделайте AppDelegate UNUserNotificationCenterDelegate:

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { 

В ваших «didFinishLaunchingWithOptions» добавить следующее:

UNUserNotificationCenter.current().delegate = self 
    UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in 
     if (granted) { 
      UIApplication.shared.registerForRemoteNotifications() 
     } else{ 
      print("Notification permissions not granted") 
     } 
    }) 

Это позволит определить, если пользователь ранее сказал, что ваше приложение может отправлять уведомления. Если нет, справитесь с этим, как вам угодно.

Чтобы получить доступ к маркеру устройства после его регистрации:

//Completed registering for notifications. Store the device token to be saved later 
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 

    self.deviceTokenString = deviceToken.hexString 
} 

шестнадцатеричного является расширением Я добавил к моему проекту:

extension Data { 
    var hexString: String { 
     return map { String(format: "%02.2hhx", arguments: [$0]) }.joined() 
    } 
} 

Чтобы справиться, что происходит, когда ваше приложение получает уведомление на переднем плане:

//Called when a notification is delivered to a foreground app. 
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 
    //Handle the notification 
    //This will get the text sent in your notification 
    let body = notification.request.content.body 

    //This works for iphone 7 and above using haptic feedback 
    let feedbackGenerator = UINotificationFeedbackGenerator() 
    feedbackGenerator.notificationOccurred(.success) 

    //This works for all devices. Choose one or the other. 
    AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil) 
} 

Чтобы справиться с тем, что произойдет, когда ваше приложение получит уведомление в фоновом режиме, после которого пользователь нажимает на уведомление:

//Called when a notification is delivered to a background app. 
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
    //Handle the notification 
    print("did receive") 
    let body = response.notification.request.content.body 
    completionHandler() 

}