在obj-C中,当另一个iOS应用程序(邮件附件、web链接)被与我的应用程序关联的文件或链接点击时.然后我会在openURL或didFinishLaunchingWithOptions上捕捉到这一点,并显示一个UIAlertView来确认用户想要导入数据.既然UIAlertView贬值了,我也在try 做同样的事情,但不确定最好的方法是什么?

当我的应用程序从另一个应用程序接收数据时,我无法显示简单alert .以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;
}

但当我try 切换到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中的代码类似于冷启动),添加或不添加新数据,取决于alert Select .

我可以标记一个全局变量,我在所有viewWillAppear func中都签入了它,但这会有很多重复,因为我有30多个视图.

如果你有任何 idea ,请告诉我.

谢谢

格雷格

推荐答案

try 使用

self.window?.rootViewController?.presentViewController(importAlert, animated: true, completion: nil)

你所需要的只是一个viewController对象来呈现AlertController.

在Swift 4中:

self.window?.rootViewController?.present(importAlert, animated: true, completion: nil)

Swift相关问答推荐

在解码字符串时需要帮助.

Variadic泛型与Swift中的值和类型参数包

OBJC代码中Swift 演员的伊瓦尔:原子还是非原子?

使用MKLocalSearch获取坐标

字典下标或运算符,如果密钥不存在,则添加指定的默认&值是SWIFT?

使用 @resultBuilder 的通用 buildList 函数

Swiftui 无法从核心数据中获取数据

XCUITest 在 TearDown 期间随机失败-无法终止 com.bundle.id

Swift初始化具有可变ID的重复值数组

无法增加系统镜像的大小

引用类型(类)不需要但 struct 需要的可识别 id

Vapor - 流利的,将对象保存到 PostgreSQL

FirebaseStorage:如何删除目录

如何实现 Swift 的 Comparable 协议?

CMutablePointer - 如何访问它?

Swift 3:小数到 Int

Facebook SDK 4.0 IOS Swift 以编程方式注销用户

更改在变量的 willSet 块中设置的值

Swift 中的可选数组与空数组

将 UIImage 剪成圆形