在 obj-C 中,当另一个 iOS 应用程序(邮件附件、网络链接)被点击了一个文件或与我的应用程序关联的链接时。然后我会在 openURL 或 didFinishLaunchingWithOptions
上捕捉到这一点,并显示一个 UIAlertView
以确认用户想要导入数据。现在 UIAlertView
已被贬值,我正在尝试做同样的事情,但不确定最好的方法是什么?
当我的应用从另一个应用接收数据时,我无法显示简单的警报。此代码在带有 UIAlertView
的 Objective-C 中运行良好:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
if (url)
{
self.URLString = [url absoluteString];
NSString *message = @"Received a data exchange request. Would you like to import it?";
importAlert = [[UIAlertView alloc] initWithTitle:@"Data Received" message:message delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
[importAlert show];
}
return YES;
}
但是当我尝试切换到 UIAlertViewController
和 Swift 时,我似乎找不到显示消息的简单方法:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
let URLString: String = url.absoluteString!
let message: String = "Received data. Would you like to import it?"
var importAlert: UIAlertController = UIAlertController(title: "Data Received", message: message, preferredStyle: UIAlertControllerStyle.Alert)
importAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
importAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler:
{ action in
switch action.style {
case .Default:
println("default")
case .Cancel:
println("cancel")
case .Destructive:
println("destructive")
}
}))
self.presentViewController(importAlert, animated: true, completion: nil)
return true
}
我收到一个编译时错误,即 AppDelegate
没有名为 presentViewController
我看到了一些复杂的方法来让 AppDelegate
在 StackOverflow 上显示 UIAlertViewController
,但我希望有一些更简单的方法。
我真正需要做的就是向用户显示他们获得了一些数据的快速消息,并让他们决定他们想用这些数据做什么。完成后,我的应用程序将继续打开并进入前台(didFinishLaunchingWithOptions
中的类似代码用于冷启动),根据警报选择添加或不添加新数据。
我可以标记我在所有 viewWillAppear
func 中检查的全局变量,但这将是很多重复,因为我有 30 多个 View 。
如果您有任何想法,请告诉我。
谢谢
格雷格
最佳答案
尝试使用
self.window?.rootViewController?.presentViewController(importAlert, animated: true, completion: nil)
您只需要一个 viewController
对象来显示 AlertController。
在 Swift 4 中:
self.window?.rootViewController?.present(importAlert, animated: true, completion: nil)
关于ios - 显示 UIAlertController 的简单 App Delegate 方法(在 Swift 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26627511/