ios - 在应用程序处于前台 Swift 3 时获取本地通知以显示

标签 ios swift swift3 uilocalnotification unusernotificationcenter

显然,这现在可以通过 ios10 实现:

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?

我只是不太明白如何将它们放在一起。

我不知道这有多重要,但我无法保留可选的 func 并且 xcode 要我将其切换为私有(private)。

我正在尝试显示角标(Badge),文档提供

static var badge: UNNotificationPresentationOptions { get }

这里有点迷路。

然后我假设如果我想排除某个 View Controller 获取这些角标(Badge)并且我没有使用导航 Controller ,那么我发现的这段代码会起作用吗? : 变种窗口:UIWindow?

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

最佳答案

有一个委托(delegate)方法可以在 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()
    }

}

为了在 iOS 10 中安排通知并提供角标(Badge)

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 ?? "some unknown error")
        }     
        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
    }

我也在这里定义了 Action 。你可以跳过它们

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

    }

如果您希望您的通知横幅在整个应用程序中随处可见,那么您可以在AppDelegate 中编写UNUserNotificationDelegate 的委托(delegate),并使UNUserNotificationCenter 当前委托(delegate)给 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

关于ios - 在应用程序处于前台 Swift 3 时获取本地通知以显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39713605/

相关文章:

ios - 如何在 Firebase 中使用通配符?

ios - 当滑动太快或连续快速左右滑动时如何跟踪 pageViewController 的索引

objective-c - NSBundle pathForResource 不工作

ios - Xcode 8.2.1 & Swift 3.0.2 + Realm 2.4.x = 致命异常崩溃

ios - 在 swift 中关闭模态 viewController 时传递数据

ios - NSLayoutConstraint 将 View 固定到父 View 的底部边缘

ios - Alamofire 仅在运行存档应用程序时崩溃

ios - 如何使用 DispatchGroup 在 for 循环中进行异步调用

ios - 如何从MasterView的TableViewCell(Xib Cell)导航到DetailView的TableView

使用变量作为索引的 Swift 元组索引?