application:didReceiveRemoteNotification:fetchComp

2019-08-13 01:44发布

问题:

I've been puzzled by this for weeks and still no idea what's going on. The app is setup with background mode to play audio and fetch data. The app is backgrounded and the screen is on lockscreen. The method

application:didReceiveRemoteNotification:fetchCompletionHandler:

gets called when a remote push arrives. The odd thing is that the application state is different sometimes. Here are the two outcomes from different sessions:

A) Remote push comes in, application state is UIApplicationStateBackground, which is exactly as expected. This allows the configured 'required background modes' in the .plist to work properly:

2015-07-18 13:26:38.273 x[22430:5297207] AppDelegate applicationWillResignActive: called
2015-07-18 13:26:39.007 x[22430:5297207] AppDelegate applicationDidEnterBackground: called
2015-07-18 13:29:04.181 x[22430:5297207] application:didReceiveRemoteNotification:fetchCompletionHandler: applicationState == UIApplicationStateBackground

B) Remote push comes in, but application state is not UIApplicationStateBackground. For some reason, the app starts its transition into the foreground before the method is called, and then state is incorrectly UIApplicationStateInactive instead of UIApplicationStateBackground inside the method:

2015-07-18 12:37:26.087 x[22430:5297207] AppDelegate applicationWillResignActive: called
2015-07-18 12:37:26.899 x[22430:5297207] AppDelegate applicationDidEnterBackground: called
2015-07-18 12:39:20.898 x[22430:5297207] AppDelegate applicationWillEnterForeground: called
2015-07-18 12:39:21.014 x[22430:5297207] application:didReceiveRemoteNotification:fetchCompletionHandler: applicationState == UIApplicationStateInactive

This state difference prevents the background mode audio from playing. Please note that the method is not in state UIApplicationStateInactive as a result of opening the app from the remote push notification. It is in that state when the remote push notification arrives and invokes the method. Anybody have any ideas why this is happening and how to prevent it?