13

Najwyraźniej jest to teraz możliwe z ios10:Pierwsze lokalne powiadomienia pokazać podczas gdy aplikacja jest w planie Swift 3

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

Ta odpowiedź w zasadzie mówi narzędzia potrzebne, aby to zrobić:

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

Po prostu nie rozumiem, jak to wszystko połączyć.

Nie wiem, jak ważne jest to, ale nie mogę zachować opcjonalnego func i xcode chce, żebym przełączył go na prywatny.

Próbuję pokazać odznakę i docs zapewnić

static var badge: UNNotificationPresentationOptions { get } 

Mała stracił tutaj.

A potem zakładam, że jeśli chcę wyłączyć kontroler widoku od otrzymywania tych identyfikatorów i nie używam kontrolera nawigacyjnego, ten kod, który znalazłem, zadziała? : Okno var: UIWindow?

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

Odpowiedz

42

Istnieje metoda delegata, aby wyświetlić powiadomienie, gdy aplikacja jest otwarty w iOS 10. Trzeba zaimplementować to w celu uzyskania bogatych powiadomienia pracy, gdy aplikacja jest otwarta.

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() 
    } 

} 

W celu planowania powiadomienia w iOS 10 i zapewniając odznakę

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") 
    } 
} 

Aby zarejestrować się w AppDelegate musimy napisać ten kawałek kodu w didFinishLaunchingWithOptions

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

Również tutaj zdefiniowałem działania.Można pominąć im

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]) 

    } 

Jeśli chcesz, aby Twoje zgłoszenie transparent należy zamieścić wszędzie w całej aplikacji, a następnie można napisać delegata UNUserNotificationDelegate w AppDelegate i dokonać UNUserNotificationCenter aktualnego delegata do 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]) 
    } 
} 

Sprawdź ten link, aby uzyskać więcej informacji
https://www.youtube.com/watch?v=Svul_gCtzck

Github Próbka
https://github.com/kenechilearnscode/UserNotificationsTutorial

Oto wynik

enter image description here

enter image description here

+0

Niesamowita, świetna odpowiedź. Dziękuję Ci. – user6820041

+0

teraz załóżmy, że chcę ustawić obraz z NSURL oznacza web, a następnie jak mogę to ustawić? –

+0

Bardzo ładna odpowiedź !! – Maybe1

6

Kluczem do uzyskania powiadomienia, aby pokazać się w czasie, gdy aplikacja jest na pierwszym planie jest również ustawienie:

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

w Twojej UNNotificationRequest. Co do reszty, zobacz doskonałą odpowiedź: Rajan Maheshwari.

+0

NIE powinieneś tego ustawiać, jeśli twój delegat dla 'UNUserNotificationCenterDelegate' i rejestracja kategorii akcji są poprawnie skonfigurowane. Pierwsza metoda w delegacie jest tam, aby przetworzyć ten przypadek w aplikacji na pierwszym planie. Ustawienie tej wartości nie jest udokumentowane i może prowadzić do odrzucenia wytycznych dotyczących sklepu z aplikacjami. – James

8

Swift 3 | iOS 10+

Zakładając wiesz jak zaplanować lokalnej powiadomienie:

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 
     } 
    } 
} 

Trzeba dokonać AppDelegate wdrożyć protokół UNUserNotificationCenterDelegate i ustawić go jako delegata Centrum powiadomień użytkownika z 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) 
    } 
} 

Teraz pojawią się lokalni powiadomienia, gdy aplikacja jest na pierwszym planie.

Zobacz dokumenty UNUserNotificationCenterDelegate w celach informacyjnych.

+0

niesamowite bro niesamowite! Charlie Sheen powiedziałby, że jesteś gwiazdą rocka! Jeśli masz powiadomienia na pierwszym planie, po prostu skopiuj i wklej ten fragment kodu i gotowe !. – Mikhail

Powiązane problemy