Can I launch an app in Foreground when I enter an

2020-02-01 19:02发布

问题:

I'm creating an app for iOS using iBeacons. I know, that if i set up a region to monitor, the framework can invoke my app when I enter/exit a region, or turn on the screen inside the region. I've managed to create a local notification in this callback as well. My question is, whether is it possible to bring the app into foreground, like if it was launched by the user?

回答1:

No, I do not believe this is possible. Apple's philosophy is that the user is in control of what app is in the foreground. The only three ways to bring an app into the foreground are: (1) tapping its icon, (2) tapping a notification associated with the app or (3) through a custom URL to launch the app from a different app.

I have a colleague who has long insisted this is possible, so I tried it myself today to see for sure. In our open source SavengerHunt app, I modified the AppDelegate's didDetermineState method to add the code below to try and force the app into the foreground.

        NSLog(@"Attempting for force window %@ into foreground", self.window);
        [self.window makeKeyAndVisible];
        NSLog(@"Done with attempt");

The code executed when an iBeacon was detected in the background, and the log lines showed up as expected. The app, however, did not change to the foreground.

       2014-03-06 11:35:43.655 scavengerhunt[277:60b] Sending a notification that a beacon is nearby
       2014-03-06 11:35:43.678 scavengerhunt[277:60b] Attempting for force window <UIWindow: 0x14e96730; frame = (0 0; 320 480); gestureRecognizers = <NSArray: 0x14e95870>; layer = <UIWindowLayer: 0x14e961f0>> into foreground
       2014-03-06 11:35:43.686 scavengerhunt[277:60b] Done with attempt

Given that this doesn't work, your best bet is to present a local notification to the user. If they tap on it, your app will move to the foreground.