Is it possible to execute a listener when the App is not running?

1

The App would have to communicate to the user, that there was a change in a value on the server, but without using Push Notification. So I thought I'd add a listener on iOS, and that when I detected the change in value, it would trigger a local notification. And this should occur even though the App is not running.

Does anyone know where I can start?

    
asked by anonymous 28.05.2015 / 06:51

1 answer

3

You can launch the app in the background, check the server and then trigger the notification, using background fetch. The steps are as follows:

  • In the project settings under Capabilities , enable the Background Modes section and select Background fetch .
  • In the AppDelegate class, in the -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions you set the frequency at which the app will be called in the background, using the method: - (void)setMinimumBackgroundFetchInterval:(NSTimeInterval)minimumBackgroundFetchInterval
  • Example:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        //...
        [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
        return YES;
    }
    
  • Now add in the AppDelete class the - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler;
  • This method will be called whenever the app is launched in the background. At the end of the execution of the operations it is always necessary to call the completionHandler , informing if the search for the data was successful. Example:

    -(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
        /*
        ...
         */
        completionHandler(UIBackgroundFetchResultNewData);
    }
    

    To test, you set the target to launch the app in background mode. To do this, go to Product / Scheme / Manage Schemes . Now at Run / Option , select Launch due to a background fetch . When you build the app it will simulate the background release so you can test it without waiting for the system to do so.

        
    28.05.2015 / 19:12