我正在编程一个iPhone应用程序,我需要强制它退出由于某些用户操作。在清理应用程序分配的内存后,调用什么方法来终止应用程序?
当前回答
这并不是一种退出项目的方法,而是一种强迫人们退出的方法。
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];
其他回答
在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
嗯,如果你的应用需要网络连接,你可能“不得不”退出应用程序。你可以显示一个警告,然后做这样的事情:
if ([[UIApplication sharedApplication] respondsToSelector:@selector(terminate)]) {
[[UIApplication sharedApplication] performSelector:@selector(terminate)];
} else {
kill(getpid(), SIGINT);
}
[[UIApplication sharedApplication] terminateWithSuccess];
它工作正常,自动调用
- (void)applicationWillTerminateUIApplication *)application delegate.
要删除编译时警告,请添加以下代码
@interface UIApplication(MyExtras)
- (void)terminateWithSuccess;
@end
你不应该直接调用函数exit(0),因为它会立即退出应用程序,看起来就像你的应用程序崩溃了。所以最好是给用户显示一个确认提醒,让他们自己去做。
斯威夫特4.2
func askForQuit(_ completion:@escaping (_ canQuit: Bool) -> Void) {
let alert = UIAlertController(title: "Confirmation!", message: "Do you want to quit the application", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
completion(true)
}))
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
completion(false)
}))
self.present(alert, animated: true, completion: nil)
}
/// Will quit the application with animation
func quit() {
UIApplication.shared.perform(#selector(NSXPCConnection.suspend))
/// Sleep for a while to let the app goes in background
sleep(2)
exit(0)
}
用法:
self.askForQuit { (canQuit) in
if canQuit {
self.quit()
}
}
在iPhone上,没有退出应用的概念。导致应用退出的唯一操作是触摸手机上的Home键,而这不是开发者可以访问的。
根据苹果公司的说法,你的应用程序不应该自行终止。因为用户没有点击Home键,所以任何返回到Home屏幕的操作都会给用户留下应用程序崩溃的印象。这是令人困惑的,不规范的行为,应该避免。
推荐文章
- NSRange从Swift Range?
- UICollectionView中的单元格间距
- 我如何在我的iOS应用程序中每n分钟得到一个后台位置更新?
- 如何使用iOS创建GUID/UUID
- 禁用所呈现视图控制器的交互式撤销
- 点击按钮时如何打开手机设置?
- 如何使用UIVisualEffectView来模糊图像?
- 如何修复UITableView分隔符在iOS 7?
- 故事板中的自定义单元格行高设置没有响应
- 如何改变时间和时区在iPhone模拟器?
- 在Swift中使用自定义消息抛出错误/异常的最简单方法?
- 如何在Swift中获得唯一的设备ID ?
- 我如何知道何时UITableView完成了ReloadData?
- 复制文本到剪贴板与iOS
- 在Swift中根据字符串计算UILabel的大小