How to exit app and return to home screen in iOS 8

2019-01-24 02:59发布

问题:

I'm trying to programmatically return to the home screen in an iOS8 App using Swift. I want to continue the application running in the background though. Any ideas on how to do this?

Thanks in advance for the help.

回答1:

When an app is launched, the system calls the UIApplicationMain function; among its other tasks, this function creates a singleton UIApplication object. Thereafter you access the object by calling the sharedApplication class method.

To exit gracefully (the iOS developer library explicitly warns you not to use exit(0) because this is logged as a crash ) you can use:

UIControl().sendAction(#selector(URLSessionTask.suspend), to: UIApplication.shared, for: nil)

For example, my app exits when the user shakes the device. So, in ViewController.swift:

override func motionEnded(motion: UIEventSubtype,
    withEvent event: UIEvent?) {

        if motion == .MotionShake{

            //Comment: to terminate app, do not use exit(0) bc that is logged as a crash.

            UIControl().sendAction(Selector("suspend"), to: UIApplication.sharedApplication(), forEvent: nil)
        }}


回答2:

Swift 4:

UIControl().sendAction(#selector(NSXPCConnection.suspend),
                       to: UIApplication.shared, for: nil)


回答3:

For that you should use following code

import Darwin
exit(0)


回答4:

To force your app into the background, you can legally launch another app, such as Safari, via a URL, into the foreground.

See: how to open an URL in Swift3

UIApplication.shared.open() (and the older openURL) are a documented public APIs.

If you set the exits-on-suspend plist key, opening another app via URL will also kill your app. The use of this key is a documented legal use of app plist keys, available for any app to "legally" use.

Also, if your app, for some impolite reason, continues to allocate and dirty large amounts of memory in the background, without responding to memory warnings, the OS will very likely kill it.



回答5:

There is no way to "programmatically return to the home screen" except for crashing, exiting your program or calling unofficial API. Neither is welcome by Apple. Plus the Human Interface Guidelines are also covering this.