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


当前回答

在iPadOS 13中,你现在可以像这样关闭所有场景会话:

for session in UIApplication.shared.openSessions {
    UIApplication.shared.requestSceneSessionDestruction(session, options: nil, errorHandler: nil)
}

这将在你的应用委托上调用applicationWillTerminate(_ application: UIApplication),并在最后终止应用。

但要注意两件事:

这当然不是用来关闭所有的场景。(参见https://developer.apple.com/design/human-interface-guidelines/ios/system-capabilities/multiple-windows/) 它在iPhone的iOS 13上编译和运行良好,但似乎什么都不做。

更多关于iOS/iPadOS 13场景的信息:https://developer.apple.com/documentation/uikit/app_and_environment/scenes

其他回答

- (IBAction)logOutButton:(id)sender
{
   //show confirmation message to user
   CustomAlert* alert = [[CustomAlert alloc] initWithTitle:@"Confirmation" message:@"Do you want  to exit?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
   alert.style = AlertStyleWhite;
   [alert setFontName:@"Helvetica" fontColor:[UIColor blackColor] fontShadowColor:[UIColor clearColor]];
   [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
      NSLog(@"exit(0)");
      exit(0);
  }
}

经过一些测试,我可以这样说:

使用私有接口:[UIApplication sharedApplication]将导致应用程序看起来像它崩溃了,但它将调用- (void)applicationWillTerminate:(UIApplication *)应用程序之前这样做; 使用退出(0);也会终止应用程序,但它看起来“正常”(跳板的图标看起来像预期的一样,有缩小效果),但它不会调用- (void)applicationWillTerminate:(UIApplication *)应用程序委托方法。

我的建议:

在委托上手动调用- (void)applicationWillTerminate:(UIApplication *)应用程序。 调用退出(0);。

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

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];

这已经得到了一个很好的答案,但我决定扩展一下:

如果你不仔细阅读苹果的iOS人机界面指南,你的应用就不可能被AppStore接受。(他们保留拒绝你做任何反对他们的事情的权利)部分“不要以编程方式退出”http://developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/MobileHIG/UEBestPractices/UEBestPractices.html 是一个明确的指导方针,告诉你应该如何处理这种情况。

如果你遇到苹果平台的问题,你很难找到解决方案,请咨询HIG。有可能苹果只是不想让你这么做,他们通常(我不是苹果,所以我不能保证总是)在他们的文档中这样说。

在application-info上添加UIApplicationExitsOnSuspend属性。请承认是真的。