0

FCMサンプルプロジェクトであっても、デバイスがバックグラウンドのときにプッシュ通知を受信できません。アプリがバックグラウンドになると iは、アプリがフォアグラウンド、また通知を受け取ることができイム来るFCMサンプルプロジェクトが通知をバックグラウンドで受信しない

プッシュ通知がbackground.When以外の他のすべてのシナリオに適していますFCMから

切断このメッセージが表示されます。誰もこの状況に直面したことがありますか?どんな考えも歓迎です。 enter image description here

私のプロジェクト

#import "AppDelegate.h" 


#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 
@import UserNotifications; 
#endif 

@import Firebase; 
@import FirebaseInstanceID; 
@import FirebaseMessaging; 

// Implement UNUserNotificationCentbberDelegate to receive display notification via APNS for devices 
// running iOS 10 and above. Implement FIRMessagingDelegate to receive data message via FCM for 
// devices running iOS 10 and above. 
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 
@interface AppDelegate()<UNUserNotificationCenterDelegate, FIRMessagingDelegate> 
@end 
#endif 

// Copied from Apple's header in case it is missing in some cases (e.g. pre-Xcode 8 builds). 
#ifndef NSFoundationVersionNumber_iOS_9_x_Max 
#define NSFoundationVersionNumber_iOS_9_x_Max 1299 
#endif 

@implementation AppDelegate 
@synthesize onlineChatConversation; 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 

    // Override point for customization after application launch. 


    // [FIRApp configure]; 

    return YES; 
} 


+ (AppDelegate *)appDelegate 
{ 
    return (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
} 

-(void)enableNotification 
{ 

    UIApplication * appinstance =[UIApplication sharedApplication]; 


    static dispatch_once_t onceToken; 
    dispatch_once (&onceToken, ^{ 
     // Do some work that happens once 


     // Register for remote notifications 
     [self EnablePushNotification:appinstance]; 



    }); 



} 
//-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ 
//  
//  
//  [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox]; 
//  
// // [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeProd]; 
//  
//} 

/* 
* Code for registering push notification 
*/ 
- (void)EnablePushNotification:(UIApplication *)appinstance{ 
     // Register for remote notifications 
     if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) { 
      // iOS 7.1 or earlier. Disable the deprecation warnings. 
#pragma clang diagnostic push 
#pragma clang diagnostic ignored "-Wdeprecated-declarations" 
      UIRemoteNotificationType allNotificationTypes = 
      (UIRemoteNotificationTypeSound | 
      UIRemoteNotificationTypeAlert | 
      UIRemoteNotificationTypeBadge); 
      [appinstance registerForRemoteNotificationTypes:allNotificationTypes]; 
#pragma clang diagnostic pop 
     } else { 
      // iOS 8 or later 
      // [START register_for_notifications] 
      if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) { 
       UIUserNotificationType allNotificationTypes = 
       (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge); 
       UIUserNotificationSettings *settings = 
       [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil]; 
       [appinstance registerUserNotificationSettings:settings]; 
      } else { 
       // iOS 10 or later 
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 
       UNAuthorizationOptions authOptions = 
       UNAuthorizationOptionAlert 
       | UNAuthorizationOptionSound 
       | UNAuthorizationOptionBadge; 
       [[UNUserNotificationCenter currentNotificationCenter] 
       requestAuthorizationWithOptions:authOptions 
       completionHandler:^(BOOL granted, NSError * _Nullable error) { 
       } 
       ]; 

       // For iOS 10 display notification (sent via APNS) 
       [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self]; 
       // For iOS 10 data message (sent via FCM) 
       [[FIRMessaging messaging] setRemoteMessageDelegate:self]; 
#endif 
      } 
      [appinstance registerForRemoteNotifications]; 
      // [END register_for_notifications] 
     } 
     // [START configure_firebase] 
     [FIRApp configure]; 
     // [END configure_firebase] 
     // Add observer for InstanceID token refresh callback. 


     NSString *refreshedToken = [[FIRInstanceID instanceID] token]; 
     NSLog(@" refreshedToken =%@",refreshedToken); 

     if (refreshedToken) { 
      [self registerUSerDevice:refreshedToken]; 
     } 
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:) 
                name:kFIRInstanceIDTokenRefreshNotification object:nil]; 

} 

// [START receive_message] 
// To receive notifications for iOS 9 and below. 
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { 
    // 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 full message. 
    NSLog(@"%@", userInfo); 

     NSString * NotifMessage = [[userInfo objectForKey:@"notification"]objectForKey:@"body"]; 
     NSString * Notiftype = [userInfo objectForKey:@"type"]; 

//  NSString * Notiftitle = [[[userInfo objectForKey:@"notification"] objectForKey:@"notification"] objectForKey:@"title"]; 
//  NSString * Notifbadge = [[[userInfo objectForKey:@"notification"] objectForKey:@"notification"] objectForKey:@"badge"]; 
//  NSString * NotifSound = [[[userInfo objectForKey:@"notification"] objectForKey:@"notification"] objectForKey:@"sound"]; 

    NSString *chatProviderId = [[NSUserDefaults standardUserDefaults] stringForKey:@"chatProviderId"]; 

    if (([Notiftype isEqual:@"message"])) { 

     if ([NotifMessage isEqualToString:@"Your mobile device added successfully to receive notifications."]){ 

     }else if([[userInfo objectForKey:@"sender_id"] isEqualToString:chatProviderId ]){ 

     } 
     else{ 

      [AGPushNoteView showWithNotificationMessage:[NSString stringWithFormat:@"%@",NotifMessage]]; 
      [AGPushNoteView setMessageAction:^(NSString *NotifMessage){ 
      NSLog(@"%@",NotifMessage); 
       if ([NotifMessage rangeOfString:@"You have new message from"].location != NSNotFound) { 
        [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"openchatpage_Notification" 
        object:userInfo]; 

       }else if ([NotifMessage rangeOfString:@"has requested for new appointment"].location != NSNotFound) 
       { 
        //NSLog(@"video consultation started %@",[userInfo objectForKey:@"key"]); 



       }else 
       { 

       } 

       //  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"PUSH" 
       //              message:message 
       //              delegate:nil 
       //            cancelButtonTitle:@"Close" 
       //            otherButtonTitles:nil]; 
       //  [alert show]; 

       //    UIStoryboard *mainStrotyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]]; 
       //    ViewCardDetails *viewCardDetails = [mainStrotyBoard instantiateViewControllerWithIdentifier:@"viewcarddetails"]; 
       //    [self.navigationController pushViewController:viewCardDetails animated:YES]; 
       //    // [self.navigationController pushViewController:forgotPasswordViewController animated:YES]; 
       //    [self presentViewController:forgotPasswordViewController animated:YES completion:nil]; 
      }]; 
     } 
} 


if (([Notiftype isEqual:@"New Appointment"]||[Notiftype isEqual:@"Quick Appointment"])) { 


     [AGPushNoteView showWithNotificationMessage:[NSString stringWithFormat:@"%@",NotifMessage]]; 

    [AGPushNoteView setMessageAction:^(NSString *NotifMessage) { 

//   [[NSNotificationCenter defaultCenter] 
//   postNotificationName:@"openApptlist_Notification" 
//   object:userInfo]; 


     [[NSNotificationCenter defaultCenter] 
      postNotificationName:@"videoconsultationStart_Notif" 
      object:userInfo]; 


    }]; 


    UIViewController * lastvc = [[UIViewController alloc]init]; 

    lastvc = [[[UIApplication sharedApplication] keyWindow] visibleViewController]; 



} 



// [START ios_10_message_handling] 
// Receive displayed notifications for iOS 10 devices. 
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 
- (void)userNotificationCenter:(UNUserNotificationCenter *)center 
     willPresentNotification:(UNNotification *)notification 
     withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { 
    // Print message ID. 
    NSDictionary *userInfo = notification.request.content.userInfo; 
    NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]); 

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

// Receive data message on iOS 10 devices. 
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage { 
    // Print full message 
    NSLog(@"%@", [remoteMessage appData]); 
} 
#endif 
// [END ios_10_message_handling] 

// [START refresh_token] 
- (void)tokenRefreshNotification:(NSNotification *)notification { 
    // Note that this callback will be fired everytime a new token is generated, including the first 
    // time. So if you need to retrieve the token as soon as it is available this is where that 
    // should be done. 
    NSString *refreshedToken = [[FIRInstanceID instanceID] token]; 
    NSLog(@"InstanceID token: %@", refreshedToken); 

    if (refreshedToken) { 
     [self registerUSerDevice:refreshedToken]; 
    } 
    // Connect to FCM since connection may have failed when attempted before having a token. 
    [self connectToFcm]; 

    // TODO: If necessary send token to application server. 
} 
// [END refresh_token] 

// [START connect_to_fcm] 
- (void)connectToFcm { 
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) { 
     if (error != nil) { 
      NSLog(@"Unable to connect to FCM. %@", error); 
     } else { 
      NSLog(@"Connected to FCM."); 
     } 
    }]; 
} 
// [END connect_to_fcm] 

- (void)applicationDidBecomeActive:(UIApplication *)application { 
    [self connectToFcm]; 
} 

// [START disconnect_from_fcm] 
- (void)applicationDidEnterBackground:(UIApplication *)application { 
    [[FIRMessaging messaging] disconnect]; 
    NSLog(@"Disconnected from FCM"); 
} 
// [END disconnect_from_fcm] 



- (void)applicationWillResignActive:(UIApplication *)application { 
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
} 


- (void)applicationWillEnterForeground:(UIApplication *)application { 
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 
} 

- (void)applicationWillTerminate:(UIApplication *)application { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
} 


-(void) registerUSerDevice:(NSString *)token{ 

    // UIAlertView *alertNotification = [[UIAlertView alloc] initWithTitle:@"2" message:@"register user device called" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
    //[alertNotification show]; 

    NSLog(@"token %@",token); 
    //Sending token to server 

    NSString * baseurl = [CustomUtility getWebserviceforKey:@"serverAddress"]; 
    NSString * apikey = [CustomUtility getWebserviceforKey:@"APIKEY"]; 
    NSString *urlString = [NSString stringWithFormat:@"%@api/mobile_profiles/add_mobile_devise",baseurl];  
    NSString *user_token = [[NSUserDefaults standardUserDefaults] stringForKey:@"USER_TOKEN"]; 


    // NSDictionary * jsonString = @{ @"user":@{@"user_token":user_token},@"api_key":@"C0VS9qojCDWTVOut251u4Y7f0H8eN8aF",@"token_id":@"token.tokenId"}; 

    NSDictionary * jsonString = @{@"user":@{@"user_token":user_token,@"devise_id":token},@"api_key":apikey}; 


    NSLog(@"jsonstring - %@",jsonString); 

    NSDictionary *headers = @{ @"content-type": @"application/json" }; 

    NSData *postData = [NSJSONSerialization dataWithJSONObject:jsonString options:0 error:nil]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0]; 

    [request setHTTPMethod:@"POST"]; 

    [request setAllHTTPHeaderFields:headers]; 

    [request setHTTPBody:postData]; 

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,NSData *data, NSError *connectionError){ 

     //  UIAlertView *alertNotification = [[UIAlertView alloc] initWithTitle:@"3" message:@"Some response came" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     // [alertNotification show]; 

     NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response; 
     int code = (int)[httpResponse statusCode]; 
     UIAlertView *alertNotification1 = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%d",code] message:@"Response" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
     // [alertNotification1 show]; 
     if (connectionError == nil && data.length > 0) { 

      if (code == 200) { 

       if (data.length > 0){ 

        // self.saveButton.enabled = YES; 

        // [self.activityindicator stopAnimating]; 
        // self.activityindicator.hidden = YES; 

        NSDictionary *follow_favorite1 = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; 
        NSLog(@"the responseString was %@", follow_favorite1); 

        if ([[follow_favorite1 objectForKey:@"success"]boolValue] == YES) { 


         // [self.navigationController popViewControllerAnimated:YES]; 

         //      UIAlertView *alertUser = [[UIAlertView alloc] initWithTitle:@"Success" message:[follow_favorite1 valueForKey:@"message"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
         // [alertUser show]; 

        }else { 

         UIAlertView *alertUser = [[UIAlertView alloc] initWithTitle:@"Error" message:[follow_favorite1 valueForKey:@"message"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
         [alertUser show]; 

        } 
       }else{ 


        UIAlertView *errorsecurityquestion = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Something went wrong" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
        [errorsecurityquestion show]; 
        // self.saveButton.enabled = YES; 
        // [self.activityindicator stopAnimating ]; 
        // self.activityindicator.hidden = YES; 


       } 

      }else{ 

      } 


     }else 
     { 

      UIAlertView *connectionerroralert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Connection error please try again" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
      [connectionerroralert show]; 
      // self.saveButton.enabled = YES; 
      // [self.activityindicator stopAnimating ]; 
      // self.activityindicator.hidden = YES; 


     } 


     //      NSDictionary *follow_favorite1 = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; 
     //      NSLog(@"the error is %@",follow_favorite1); 


    }]; 
} 


@end 
+0

はこれを試してhttp://stackoverflow.com/a/37899773/1142743:

詳細については、これらの関連SOの質問をチェック – Vinodh

答えて

1

のappdelegateはあなたのInfo.plistには「NO」FirebaseAppDelegateProxyEnabledタイプ「ブール」値を作り、あなたはまだ任意の通知を受信して​​いないかどうかを確認してください。この問題のもう1つの解決策は、アプリがバックグラウンドにある間に通知を表示するために、メッセージの優先度を「高」に設定することです。

関連する問題