简体   繁体   中英

How to open the app from the background task in iOS?

Is it possible to open an app from a background task in iOS?

I want my app to run in the background, and I want it to reappear for whatever reason without user input. Is this possible?

In Android you can have a service that runs in the background, and at any time you can start an Activity, which starts the app for that activity.

I know this does not make for a good user experience. I still want to know whether it can be done.

You can create schedule a local notification with a time offset of 0 (eg show an alert immediatly). If the use taps on the notification, the app will be launched.

But otherwise, you will not be able to launch out of the background into the forground without a notification.

    NSDate * theDate = [[NSDate date] dateByAddingTimeInterval:0]; //

    UIApplication* app = [UIApplication sharedApplication];
    NSArray  *    oldNotifications = [app scheduledLocalNotifications];


    // Clear out the old notification before scheduling a new one.
    if ([oldNotifications count] > 0)
        [app cancelAllLocalNotifications];

    // Create a new notification.
    UILocalNotification* alarm = [[UILocalNotification alloc] init];
    if (alarm)
    {
        alarm.fireDate = theDate;
        alarm.timeZone = [NSTimeZone defaultTimeZone];
        alarm.repeatInterval = 0;
        alarm.soundName = @"sonar";
        alarm.alertBody = @"Background task complete, tap to show app" ;

        [app scheduleLocalNotification:alarm];
    }

From Apples Documentation: "Notifications are a way for an app that is suspended, is in the background, or is not running to get the user's attention. Apps can use local notifications to display alerts, play sounds, badge the app's icon, or a combination of the three. For example, an alarm clock app might use local notifications to play an alarm sound and display an alert to disable the alarm. When a notification is delivered to the user, the user must decide if the information warrants bringing the app back to the foreground. (If the app is already running in the foreground, local notifications are delivered quietly to the app and not to the user.)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM