Nakib
Nakib

Reputation: 4713

Handling notification like whatsapp when application is forcefully close in iOS?

I am creating a chat messenger app like whatsapp and trying to implement notification functionality similar to whatsapp. In whatsapp when you receive a notification it stores the data somewhere and when you turn off your wifi and go into the app the message is injected in the application. This mean whatsapp is somehow accessing the notification even when application is closed.

My Approach: I am receiving notification in background mode and saving that into a file. So if the user gets disconnected from the internet and goes into the app the messages are still injected on applicationWillAppear. This works perfect but when you forcefully close your app (Double clicking home and swiping the app up) it does not work. I have search almost everything and it says background fetch will not work if you forcefully close your application.

Then how whatsapp is doing it? What can be any other solution?

My Solution:

Turned on Background Modes for Background Fetch and remote notification from XCode. Next added following code inside application:willFinishLaunchingWithOptions:

[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];

Added this in AppDelegate.m file

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler{

  NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);

  if (0 < [paths count]) {
    NSString *documentsDirPath = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirPath stringByAppendingPathComponent:@"notification.txt"];

    NSString *content = [NSString stringWithFormat:@"%@", userInfo];
    NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath]) {
      // Append text to the end of file
      NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:filePath];
      [fileHandler seekToEndOfFile];
      [fileHandler writeData:data];
      [fileHandler closeFile];
    } else {
      // Create the file and write text to it.
      [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
  }

  handler(UIBackgroundFetchResultNewData);

}

Update: I do have following flag in my notification

content-available: 1

Upvotes: 4

Views: 2242

Answers (1)

Scrungepipes
Scrungepipes

Reputation: 37581

Background pushes do not get delivered to a user-terminated app.

Unless it is a voip push, in that case the app will be started by the OS if necessary (but yes you can only make use of voip push if your app provides voip functionality to the user.)

Upvotes: 3

Related Questions