2016-09-22 18 views
2

私のアプリがフォアグラウンドにあるときにローカル通知を表示しようとしています。リモート通知を表示するのに問題はありませんが、アプリケーションがフォアグラウンドで実行されているときに問題が発生しています。私は新しいiOS 10にのみ問題があります。xcode 8と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を実行しており、「はい」と表示されています。私のアプリは必要な通知パーミッションを持っています。

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で発生します。私はしばらくの間Googleを検索してきましたが、私はまだそこにいません。どんな助けや提案も大歓迎です。

+0

これはあなたを助けるはずです:https://makeapppie.com/2016/08/08/how-to-make-local-notifications-in-ios-10/#comments – Do2

+0

Objective-Cメソッドでhttp:// stackoverflow。 com/questions/37938771/uilocalnotification-is-deprecated-in-ios10/37969401#37969401 – ElonChan

答えて

3

コードがiOS10では動作しません。あなた、あなたはクライアントアプリがであるときに受信通知を処理するためにAppDelegate application:didReceiveRemoteNotification:を実装し、以下のiOS 9を実行しているデバイスでは

UserNotificationsフレームワーク

を使用する必要があります。前景

iOS 10以上を実行するデバイスの場合、

UNUserNotificationCenterDelegate userNotificationCenter:willPresentNotification:withCompletionHandler: 
ここから

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

クライアントアプリがフォアグラウンドにあるときに通知を処理するため

は、あなたのコードは、(Firebase通知用)のようなものでなければならない

(ここ https://firebase.google.com/docs/notifications/ios/console-audienceから)受け取りました
関連する問題