13

Видимо, это теперь возможно с ios10:Получение местных уведомлений, чтобы показать, в то время как приложение на переднем плане Swift 3

optional func userNotificationCenter(_ center: UNUserNotificationCenter, 
       willPresent notification: UNNotification, 
    withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) 

Этот ответ в основном говорит, что инструменты, необходимые, чтобы сделать это:

Displaying a stock iOS notification banner when your app is open and in the foreground?

Я просто не понимаю, как собрать все это вместе.

Я не знаю, насколько это важно, но я не могу сохранить дополнительные функции, и xcode хочет, чтобы я переключил его на приватный.

Я пытаюсь показать значок, и документы обеспечивают

static var badge: UNNotificationPresentationOptions { get } 

немного потерял здесь.

И затем я предполагаю, что если я хочу исключить определенный контроллер просмотра из этих значков, и я не использую контроллер навигации, этот код, который я нашел, будет работать? : var window: UIWindow?

if let viewControllers = window?.rootViewController?.childViewControllers { 
for viewController in viewControllers { 
    if viewController.isKindOfClass(MyViewControllerClass) { 
     print("Found it!!!") 
     } 
    } 
} 

ответ

42

Существует метод делегата, чтобы отобразить уведомление, когда приложение работает в IOS 10. Вы должны реализовать это для того, чтобы получить богатые уведомления рабочих, когда приложение открыто.

extension ViewController: UNUserNotificationCenterDelegate { 

    //for displaying notification when app is in foreground 
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { 

     //If you don't want to show notification when app is open, do something here else and make a return here. 
     //Even you you don't implement this delegate method, you will not see the notification on the specified controller. So, you have to implement this delegate and make sure the below line execute. i.e. completionHandler. 

     completionHandler([.alert, .badge, .sound]) 
    } 

    // For handling tap and user actions 
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 

     switch response.actionIdentifier { 
     case "action1": 
      print("Action First Tapped") 
     case "action2": 
      print("Action Second Tapped") 
     default: 
      break 
     } 
     completionHandler() 
    } 

} 

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

override func viewDidLoad() { 
    super.viewDidLoad() 

    // set UNUserNotificationCenter delegate to self 
    UNUserNotificationCenter.current().delegate = self 
    scheduleNotifications() 
} 

func scheduleNotifications() { 

    let content = UNMutableNotificationContent() 
    let requestIdentifier = "rajanNotification" 

    content.badge = 1 
    content.title = "This is a rich notification" 
    content.subtitle = "Hello there, I am Rajan Maheshwari" 
    content.body = "Hello body" 
    content.categoryIdentifier = "actionCategory" 
    content.sound = UNNotificationSound.default() 

    // If you want to attach any image to show in local notification 
    let url = Bundle.main.url(forResource: "notificationImage", withExtension: ".jpg") 
    do { 
     let attachment = try? UNNotificationAttachment(identifier: requestIdentifier, url: url!, options: nil) 
     content.attachments = [attachment!] 
    }  

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 3.0, repeats: false) 

    let request = UNNotificationRequest(identifier: requestIdentifier, content: content, trigger: trigger) 
    UNUserNotificationCenter.current().add(request) { (error:Error?) in 

     if error != nil { 
      print(error?.localizedDescription) 
     }  
     print("Notification Register Success") 
    } 
} 

Для того, чтобы зарегистрироваться в AppDelegate мы должны написать этот кусок кода в didFinishLaunchingWithOptions

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     // Override point for customization after application launch. 
     registerForRichNotifications() 
     return true 
    } 

Я также определил действия здесь.Вы можете пропустить их

func registerForRichNotifications() { 

     UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) { (granted:Bool, error:Error?) in 
      if error != nil { 
       print(error?.localizedDescription) 
      } 
      if granted { 
       print("Permission granted") 
      } else { 
       print("Permission not granted") 
      } 
     } 

     //actions defination 
     let action1 = UNNotificationAction(identifier: "action1", title: "Action First", options: [.foreground]) 
     let action2 = UNNotificationAction(identifier: "action2", title: "Action Second", options: [.foreground]) 

     let category = UNNotificationCategory(identifier: "actionCategory", actions: [action1,action2], intentIdentifiers: [], options: []) 

     UNUserNotificationCenter.current().setNotificationCategories([category]) 

    } 

Если вы хотите, чтобы ваше уведомление баннер должен быть показан везде во всем приложении, то вы можете написать делегат UNUserNotificationDelegate в AppDelegate и сделать UNUserNotificationCenter текущего делегата AppDelegate

extension AppDelegate: UNUserNotificationCenterDelegate { 

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping() -> Void) { 
     print(response.notification.request.content.userInfo) 
     completionHandler() 
    } 

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void { 
     completionHandler([.alert, .badge, .sound]) 
    } 
} 

Проверить эту ссылку для получения более подробной информации
https://www.youtube.com/watch?v=Svul_gCtzck

Github Образец
https://github.com/kenechilearnscode/UserNotificationsTutorial

Вот выход

enter image description here

enter image description here

+0

Удивительный, удивительный ответ. Спасибо. – user6820041

+0

теперь предположим, что я хочу установить изображение из NSURL, означает сеть, тогда как я могу установить это? –

+0

Очень хороший ответ! – Maybe1

6

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

content.setValue(true, forKey: "shouldAlwaysAlertWhileAppIsForeground") 

в вашем UNNotificationRequest. Что касается остальных, см. Отличный ответ Rajan Maheshwari.

+0

Вам не нужно устанавливать это, если ваш делегат для 'UNUserNotificationCenterDelegate' и регистрация категории действия настроены правильно. Первый метод в делегате - это процесс для этого приложения в переднем плане. Установка этого значения недокументирована и может нарушить правила хранения приложений. – James

8

Swift 3 | IOS 10+

Предполагая, что вы знаете, как планировать локальное оповещение:

func scheduleLocalNotification(forDate notificationDate: Date) { 

    let calendar = Calendar.init(identifier: .gregorian) 

    let requestId: String = "123" 
    let title: String = "Notification Title" 
    let body: String = "Notification Body" 

    // construct notification content 
    let content = UNMutableNotificationContent() 
    content.title = NSString.localizedUserNotificationString(forKey: title, arguments: nil) 
    content.body = NSString.localizedUserNotificationString(forKey: body, arguments: nil) 
    content.sound = UNNotificationSound.default() 
    content.badge = 1 
    content.userInfo = [ 
     "key1": "value1" 
    ] 

    // configure trigger 
    let calendarComponents: [Calendar.Component] = [.year, .month, .day, .hour, .minute] 
    let dateComponents = calendar.dateComponents(calendarComponents, from: notificationDate) 
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) 

    // create the request 
    let request = UNNotificationRequest.init(identifier: requestId, content: content, trigger: trigger) 

    // schedule notification 
    UNUserNotificationCenter.current().add(request) { (error: Error?) in 
     if let error = error { 
      // handle error 
     } 
    } 
} 

Вы должны сделать свой AppDelegate реализовать протокол UNUserNotificationCenterDelegate, и установить его в качестве делегата в уведомлении центра с UNUserNotificationCenter.current().delegate = self.

// AppDelegate.swift 

import UIKit 
import UserNotifications 

@UIApplicationMain 
class AppDelegate: UIResponder, UIApplicationDelegate { 

    func application(_ application: UIApplication, didFinishLaunchingWithOptions 
     launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 

     // set app delegate as notification center delegate 
     UNUserNotificationCenter.current().delegate = self 
    } 
} 

extension AppDelegate: UNUserNotificationCenterDelegate { 

    // called when user interacts with notification (app not running in foreground) 
    func userNotificationCenter(_ center: UNUserNotificationCenter, 
     didReceive response: UNNotificationResponse, withCompletionHandler 
     completionHandler: @escaping() -> Void) { 

     // do something with the notification 
     print(response.notification.request.content.userInfo) 

     // the docs say you should execute this asap 
     return completionHandler() 
    } 

    // called if app is running in foreground 
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent 
     notification: UNNotification, withCompletionHandler completionHandler: 
     @escaping (UNNotificationPresentationOptions) -> Void) { 

     // show alert while app is running in foreground 
     return completionHandler(UNNotificationPresentationOptions.alert) 
    } 
} 

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

См. Документы UNUserNotificationCenterDelegate для справки.

+0

awesome bro awesome! Чарли Шин сказал бы, что вы рок-звезда! Если у вас есть уведомления переднего плана, просто скопируйте и вставьте этот фрагмент кода, и все готово !. – Mikhail