使用 UIAlertController 退出应用程序

Posted

技术标签:

【中文标题】使用 UIAlertController 退出应用程序【英文标题】:Exit application using a UIAlertController 【发布时间】:2016-04-04 15:03:54 【问题描述】:

如果用户在没有互联网连接的情况下打开应用程序,则会弹出一个窗口,提示需要连接,并且有一个确定按钮。我想按确定按钮退出应用程序。这是我所拥有的:

if !isConnectedToNetwork()
    let alert = UIAlertController(title: "No Internet", message: "You need an internet connection to use this app", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
    self.presentViewController(alert, animated: true, completion: nil)

我将使用它来退出应用程序:

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

我只是不知道如何将它连接到上面的确定按钮。

【问题讨论】:

这就是handler 参数在UIAlertAction 中的用途。 您使用的是 Apple 的可达性吗?如果是这样,您可以在屏幕上显示一条消息并禁用用户交互。当 Internet 连接恢复时,您可以启用用户交互并删除消息。在这种情况下,我会使用标签而不是警报。 【参考方案1】:

不要。 Apple 会拒绝(如果他们看到的话)。

只需通知用户并添加“重试”按钮即可。重试按钮显然应该再次检查连接。

要真正回答这个问题,您目前已经在按钮操作上设置了handler: nil,相反,您可以实际设置一个处理程序并使用它来调用您喜欢的任何逻辑。

【讨论】:

这实际上并没有回答问题。这是一个很好的评论,但不是问题的答案。 谢谢你的回答,我在网上查了一下,苹果会拒绝这个的原因是他们会把它当作应用程序崩溃吗?【参考方案2】:

用户按OK时可以通过以下代码进行处理

alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,
handler:  (action:UIAlertAction!) -> Void in
   //after user press ok, the following code will be execute
   NSLog("User pressed OK!!")
))

【讨论】:

以上是关于使用 UIAlertController 退出应用程序的主要内容,如果未能解决你的问题,请参考以下文章

试图用未知的演示者解除 UIAlertController

使用 UIAlertController 在 UIImagePicker 中“应用程序试图以模态方式呈现活动控制器”

如何从 Appdelegate 显示 UIAlertController

UIAlertView 和 UIAlertController

将dismissViewController 与UIAlertController 一起使用

Swift UIAlertController的用法