How to run some code in background fetch in Suspended?

How can i run some code then i got "Push notification"? in Objective c.


Then my app is running i got push notification, but then my app is closed i got nothing. but not push notification in Suspended), but can't run some code


My Code Here.

#import "AppDelegate.h"

@import Firebase;
@import FirebaseMessaging;
@import UserNotifications;

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [FIRApp configure];
    
    //Add an observer for handling a token refresh callback    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshCallBack) name:kFIRInstanceIDTokenRefreshNotification object:nil];
    
    //Request Permission for Notifications from the user
    UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
    

    //Request a device token from apple Push Notification Service
    [application registerUserNotificationSettings:settings];
    [application registerForRemoteNotifications];
    //
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveSuspendNotification:)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];

    
    return YES;
}


- (void)applicationDidFinishLaunching:(NSNotification *)notification {
    // Configure the user interactions first.
    
    backgroundlogs(@"Yes");
}

- (void) receiveSuspendNotification:(NSNotification*)notif
{
    backgroundlogs(@"run some code");
}

- (void)applicationSignificantTimeChange:(UIApplication *)application{
    backgroundlogs(@"run some code 1");
}

- (void)didReceiveObjList:(CFDataRef)message
{
    // Received Object List. Processing the list can take a few seconds.
    // So doing it in separate thread with expiration handler to ensure it gets some time to do     the task even if the app goes to background.
    
    UIApplication *application = [UIApplication sharedApplication];
    __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
        
    });
    
    backgroundlogs(@"Main Thread proceeding...");
    
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler
{
    backgroundlogs( @"Handle push from background or closed" );
    [FIRApp configure];
}

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier
  completionHandler:(void (^)())completionHandler {
    
    backgroundlogs(@"identifier outside");
    //add notification
    [self presentNotification];
}

-(void)presentNotification{
    UILocalNotification* localNotification = [[UILocalNotification alloc] init];
    localNotification.alertBody = @"Upload Complete!";
    localNotification.alertAction = @"Background Transfer Upload!";
    
    backgroundlogs(@"identifier inside");
    
    //On sound
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    
    //increase the badge number of application plus 1
    localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
    
    [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}

-(void)application:(UIApplication *)application
performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    backgroundlogs(@"Fetch");
} 

-(BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    return true;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSDictionary *payload = [userInfo objectForKey:@"aps"];
    NSString *alertMessage = [payload objectForKey:@"alert"];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:alertMessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    backgroundlogs(@"Push from EasyInstall 01");
    
    [alertView show];
}




- (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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
    
    backgroundlogs(@"Push from EasyInstall 1");
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    backgroundlogs(@"Push from EasyInstall 2");
    [[FIRMessaging messaging] disconnect];
    NSLog(@"Disconnected from FCM");
}

- (void)applicationDidChangeBackgroundRefreshStatus:(NSNotification *)notification
{
    backgroundlogs(@"write some code");
}

- (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 notication lunching the apple.
    
//    backgroundlogs(@"true");
    
    //Print message ID.
    NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]);

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

    backgroundlogs(@"AppDelegate.m: The App Got Push!");
    backgroundlogs(userInfo);
    
    backgroundlogs(@"Push from EasyInstall 3");
    
//    DisplayAlert(@"Please enable Permission from Settings->App Name->Notifications->Allow Notifications");
}

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


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    [self connectToFirebase];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    backgroundlogs(@"Push from EasyInstall 5");
}

#pragma mark -- Custom Firebase code

- (void)tokenRefreshCallBack:(NSNotification *)notification {
    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"Instance ID: %@", refreshedToken);
    
    backgroundlogs(@"Push from EasyInstall 6");
    
    //Connect to FCM since connection may have failed when attempted before haveing a token.
    [self connectToFirebase];
}

//connect to firebase NSLog !
- (void)connectToFirebase {
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if(error != nil){
            NSLog(@"Unable to connect to FCM. %@", error);

        }
        else{
            NSLog(@"Connected to FCM.");

        }
    }];
    
    backgroundlogs(@"Push from EasyInstall 7");
}

- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
    NSLog(@"FCM registration token: %@", fcmToken);
    
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}

void backgroundlogs (NSString* name)
{
    //Date formatter
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
    
    NSDate *currentDate = [NSDate date];
    NSString *dateString = [formatter stringFromDate:currentDate];
    //Date formatter
    
    //Read File
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [pathArray objectAtIndex:0];
    NSString *textPath = [documentsDirectory stringByAppendingPathComponent:@"logs.txt"];
    NSError *error = nil;
    NSString *str = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error];
    //Read File
    
    NSString *newlinee = [NSString stringWithFormat:@"%@\n%@: %@", str, dateString, name];
    
    //Write file
    NSString *zStr = newlinee;
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *directory = [paths objectAtIndex:0];
    NSString *fileName = @"logs.txt";
    NSString *filePath = [directory stringByAppendingPathComponent:fileName];
    [zStr writeToFile:filePath atomically:YES encoding:NSASCIIStringEncoding error:nil];
    //Write file
}
}

@end