我正在编程一个iPhone应用程序,我需要强制它退出由于某些用户操作。在清理应用程序分配的内存后,调用什么方法来终止应用程序?


当前回答

在iPhone上,没有退出应用的概念。导致应用退出的唯一操作是触摸手机上的Home键,而这不是开发者可以访问的。

根据苹果公司的说法,你的应用程序不应该自行终止。因为用户没有点击Home键,所以任何返回到Home屏幕的操作都会给用户留下应用程序崩溃的印象。这是令人困惑的,不规范的行为,应该避免。

其他回答

嗯,如果你的应用需要网络连接,你可能“不得不”退出应用程序。你可以显示一个警告,然后做这样的事情:

if ([[UIApplication sharedApplication] respondsToSelector:@selector(terminate)]) {
    [[UIApplication sharedApplication] performSelector:@selector(terminate)];
} else {
    kill(getpid(), SIGINT); 
}

在iPhone上,没有退出应用的概念。导致应用退出的唯一操作是触摸手机上的Home键,而这不是开发者可以访问的。

根据苹果公司的说法,你的应用程序不应该自行终止。因为用户没有点击Home键,所以任何返回到Home屏幕的操作都会给用户留下应用程序崩溃的印象。这是令人困惑的,不规范的行为,应该避免。

这并不是一种退出项目的方法,而是一种强迫人们退出的方法。

UIAlertView *anAlert = [[UIAlertView alloc] initWithTitle:@"Hit Home Button to Exit" message:@"Tell em why they're quiting" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[anAlert show];

Exit(0)在用户面前显示为崩溃,因此向用户显示确认消息。确认后暂停(home键按程序),等待2秒,应用程序将进入后台动画,然后退出用户视图

-(IBAction)doExit
{
    //show confirmation message to user
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Confirmation"
                                                 message:@"Do you want to exit?"
                                                delegate:self
                                       cancelButtonTitle:@"Cancel"
                                       otherButtonTitles:@"OK", nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != 0)  // 0 == the cancel button
    {
        //home button press programmatically
        UIApplication *app = [UIApplication sharedApplication];
        [app performSelector:@selector(suspend)];

        //wait 2 seconds while app is going background
        [NSThread sleepForTimeInterval:2.0];

        //exit app when app is in background
        exit(0);
    }
}

点击这里查看问答:https://developer.apple.com/library/content/qa/qa1561/_index.html

Q: How do I programmatically quit my iOS application? There is no API provided for gracefully terminating an iOS application. In iOS, the user presses the Home button to close applications. Should your application have conditions in which it cannot provide its intended function, the recommended approach is to display an alert for the user that indicates the nature of the problem and possible actions the user could take — turning on WiFi, enabling Location Services, etc. Allow the user to terminate the application at their own discretion. WARNING: Do not call the exit function. Applications calling exit will appear to the user to have crashed, rather than performing a graceful termination and animating back to the Home screen. Additionally, data may not be saved, because -applicationWillTerminate: and similar UIApplicationDelegate methods will not be invoked if you call exit. If during development or testing it is necessary to terminate your application, the abort function, or assert macro is recommended