Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exit app and return to home screen in iOS 8 using Swift programming

Tags:

swift

iphone

ios8

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.

like image 364
Dave Tsay Avatar asked Oct 22 '14 15:10

Dave Tsay


People also ask

What does exit () do in Swift?

exit() Terminates the current thread.

How do I exit an app in Xcode?

Swipe left on any open apps you want to close. This will move the window to the left and reveal a red X. Tap the X to close the app.

How do I keep apps from running in the background in Swift?

First, go to your project's settings and choose the Capabilities tab. You need to enable the Background Modes capability, then check the box marked Background Fetch. This modifies your app's Info. plist file to add the “fetch” background mode that enables all the following functionality.


1 Answers

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)
        }}
like image 65
reinaH Avatar answered Oct 16 '22 15:10

reinaH