场景:用户点击视图控制器上的按钮.视图控制器是导航堆栈中最顶层的(显然).tap会调用另一个类上调用的实用程序类方法.在那里发生了一件坏事,我希望在控制返回到视图控制器之前在那里显示警报.
+ (void)myUtilityMethod {
// do stuff
// something bad happened, display an alert.
}
Run Code Online (Sandbox Code Playgroud)
这是可能的UIAlertView
(但可能不太合适).
在这种情况下,你如何呈现一个UIAlertController
,就在那里myUtilityMethod
?
在obj-C中,当使用与我的应用程序关联的文件或链接轻触另一个iOS应用程序(邮件附件,Web链接)时.然后我会在openURL上捕获它,didFinishLaunchingWithOptions
并显示一个UIAlertView
确认用户想要导入数据.现在这UIAlertView
是折旧的我试图做同样的事情,但不是真的确定最好的方法来做到这一点?
当我的应用程序从另一个应用程序接收数据时,我无法显示简单警报.此代码在Objective-C中运行良好,具有UIAlertView
:
- (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;
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试切换到UIAlertViewController
Swift时,我似乎找不到一种简单的方法来显示消息:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
let URLString: String = url.absoluteString!
let message: …
Run Code Online (Sandbox Code Playgroud) 我读了这篇文章和这一个关于如何调用presentViewController形式的UIViewController子类之外.在我的例子中,自定义类是NSObject的子类.以下方法是唯一有效的方法(从我读过的例子):
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)
我的问题:是否有一个更好的解决方案,不依赖于appDelegate(因为我知道这种方法在设计方面不是很整洁)......