菜鸟教程小白 发表于 2022-12-12 12:07:30

ios - xcode 8 和 iOS 10 本地通知


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

<pre><code>func application(application: UIApplication, didReceiveRemoteNotification userInfo: ,
               fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -&gt; Void) {
    // TODO: Handle data of notification

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

            if (userInfo[&#34;notice&#34;] != nil) {

                if #available(iOS 10.0, *) {

                  print (&#34;yes&#34;)

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

                else
                {
                  let localNotification = UILocalNotification()
                  localNotification.fireDate = NSDate(timeIntervalSinceNow:0)
                  localNotification.alertBody = userInfo[&#34;notice&#34;] 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)
                }

            }

      })}
}
</code></pre>

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

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

<p>正如在 iOS 9 设备上所提到的,代码可以正常工作,并且当应用程序未运行时我会收到通知。当应用程序处于前台时,问题出在 iOS 10 上。我已经在谷歌搜索了一段时间,但我仍然不在那里。任何帮助或建议将不胜感激。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您的代码在 iOS10 中不起作用,必须使用 </p>

<blockquote>
<p>UserNotifications framework</p>
</blockquote>

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

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

<pre><code>UNUserNotificationCenterDelegate userNotificationCenter:willPresentNotification:withCompletionHandler:
</code></pre>

<p>当客户端应用程序在前台时处理收到的通知(从这里 <a href="https://firebase.google.com/docs/notifications/ios/console-audience" rel="noreferrer noopener nofollow">https://firebase.google.com/docs/notifications/ios/console-audience</a>)</p>

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

<pre><code>import UIKit
import UserNotifications

import Firebase
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: ?) -&gt; Bool {

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


    //

    FIRApp.configure()

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

    return true
}

//
func application(application: UIApplication, didReceiveRemoteNotification userInfo: ,
                   fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -&gt; 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(&#34;Message ID: \(userInfo[&#34;gcm.message_id&#34;]!)&#34;)

    // Print full message.
    print(&#34;%@&#34;, userInfo)
}
//

//
func tokenRefreshNotification(notification: NSNotification) {
    if let refreshedToken = FIRInstanceID.instanceID().token() {
      print(&#34;InstanceID token: \(refreshedToken)&#34;)
    }

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

//
func connectToFcm() {
    FIRMessaging.messaging().connectWithCompletion { (error) in
      if (error != nil) {
      print(&#34;Unable to connect with FCM. \(error)&#34;)
      } else {
      print(&#34;Connected to FCM.&#34;)
      }
    }
}
//

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

//
func applicationDidEnterBackground(application: UIApplication) {
    FIRMessaging.messaging().disconnect()
    print(&#34;Disconnected from FCM.&#34;)
}
//
}

//
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

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

    // Print full message.
    print(&#34;%@&#34;, userInfo)
}
}

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

//
</code></pre>

<p>从这里:<a href="https://github.com/firebase/quickstart-ios/blob/master/messaging/FCMSwift/AppDelegate.swift" rel="noreferrer noopener nofollow">https://github.com/firebase/quickstart-ios/blob/master/messaging/FCMSwift/AppDelegate.swift</a> </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - xcode 8 和 iOS 10 本地通知,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/39628531/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/39628531/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - xcode 8 和 iOS 10 本地通知