• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - xcode 8 和 iOS 10 本地通知

[复制链接]
菜鸟教程小白 发表于 2022-12-12 12:07:30 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试在我的应用处于前台时显示本地通知。显示远程通知没有问题,但是当应用程序在前台运行时出现问题。我只是在使用新的 iOS 10 时遇到问题。

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                 fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // TODO: Handle data of notification

if application.applicationState == UIApplicationState.Active {
    //print("Message ID: \(userInfo["gcm.message_id"]!)")
    //print("Message ID: \(userInfo.keys)")
        dispatch_async(dispatch_get_main_queue(), { () -> Void in

            if (userInfo["notice"] != nil) {

                if #available(iOS 10.0, *) {

                    print ("yes")

                    let content = UNMutableNotificationContent()
                    content.title = "My Car Wash"
                    content.body = (userInfo["notice"] as? String)!
                }

                else
                {
                    let localNotification = UILocalNotification()
                    localNotification.fireDate = NSDate(timeIntervalSinceNow:0)
                    localNotification.alertBody = userInfo["notice"] as? String
                    localNotification.soundName = UILocalNotificationDefaultSoundName

                    localNotification.alertAction = nil
                    localNotification.timeZone = NSTimeZone.defaultTimeZone()
                    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
                    let systemSoundID: SystemSoundID = 1000
                    // to play sound
                    AudioServicesPlaySystemSound (systemSoundID)
                    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
                    completionHandler(.NewData)
                }

            }

        })}
}

我的 iPhone 运行的是 iOS 10,我可以看到打印出"is"。我的应用具有所需的通知权限。

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Register for remote notifications
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
        application.registerUserNotificationSettings(settings)
        application.registerForRemoteNotifications()
        // [END register_for_notifications]
        FIRApp.configure()
        // Add observer for InstanceID token refresh callback.
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.tokenRefreshNotification),
                                                         name: kFIRInstanceIDTokenRefreshNotification, object: nil)
        return true
    }

正如在 iOS 9 设备上所提到的,代码可以正常工作,并且当应用程序未运行时我会收到通知。当应用程序处于前台时,问题出在 iOS 10 上。我已经在谷歌搜索了一段时间,但我仍然不在那里。任何帮助或建议将不胜感激。



Best Answer-推荐答案


您的代码在 iOS10 中不起作用,必须使用

UserNotifications framework

对于运行 iOS 9 及更低版本的设备,实现 AppDelegate application:didReceiveRemoteNotification: 以处理客户端应用在前台时收到的通知

对于运行 iOS 10 及更高版本的设备,实现

UNUserNotificationCenterDelegate userNotificationCenter:willPresentNotification:withCompletionHandler:

当客户端应用程序在前台时处理收到的通知(从这里 https://firebase.google.com/docs/notifications/ios/console-audience)

您的代码必须是这样的(对于 Firebase 通知):

import UIKit
import UserNotifications

import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?

  func application(application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    // [START register_for_notifications]
    if #available(iOS 10.0, *) {
      let authOptions : UNAuthorizationOptions = [.Alert, .Badge, .Sound]
      UNUserNotificationCenter.currentNotificationCenter().requestAuthorizationWithOptions(
        authOptions,
        completionHandler: {_,_ in })

      // For iOS 10 display notification (sent via APNS)
      UNUserNotificationCenter.currentNotificationCenter().delegate = self
      // For iOS 10 data message (sent via FCM)
      FIRMessaging.messaging().remoteMessageDelegate = self

    } else {
      let settings: UIUserNotificationSettings =
      UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
      application.registerUserNotificationSettings(settings)
      application.registerForRemoteNotifications()
    }


    // [END register_for_notifications]

    FIRApp.configure()

    // Add observer for InstanceID token refresh callback.
    NSNotificationCenter.defaultCenter().addObserver(self,
        selector: #selector(self.tokenRefreshNotification),
        name: kFIRInstanceIDTokenRefreshNotification,
        object: nil)

    return true
  }

  // [START receive_message]
  func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                   fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
  }
  // [END receive_message]

  // [START refresh_token]
  func tokenRefreshNotification(notification: NSNotification) {
    if let refreshedToken = FIRInstanceID.instanceID().token() {
      print("InstanceID token: \(refreshedToken)")
    }

    // Connect to FCM since connection may have failed when attempted before having a token.
    connectToFcm()
  }
  // [END refresh_token]

  // [START connect_to_fcm]
  func connectToFcm() {
    FIRMessaging.messaging().connectWithCompletion { (error) in
      if (error != nil) {
        print("Unable to connect with FCM. \(error)")
      } else {
        print("Connected to FCM.")
      }
    }
  }
  // [END connect_to_fcm]

  func applicationDidBecomeActive(application: UIApplication) {
    connectToFcm()
  }

  // [START disconnect_from_fcm]
  func applicationDidEnterBackground(application: UIApplication) {
    FIRMessaging.messaging().disconnect()
    print("Disconnected from FCM.")
  }
  // [END disconnect_from_fcm]
}

// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(center: UNUserNotificationCenter,
                              willPresentNotification notification: UNNotification,
    withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
  }
}

extension AppDelegate : FIRMessagingDelegate {
  // Receive data message on iOS 10 devices.
  func applicationReceivedRemoteMessage(remoteMessage: FIRMessagingRemoteMessage) {
    print("%@", remoteMessage.appData)
  }
}

// [END ios_10_message_handling]

从这里:https://github.com/firebase/quickstart-ios/blob/master/messaging/FCMSwift/AppDelegate.swift

关于ios - xcode 8 和 iOS 10 本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39628531/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap