ios - 打开时处理错误URL的正确方法

标签 ios swift url

任务很简单。使用给定的urlString在有效时将其打开。这是我尝试的:

func openURL(_ urlString: String) {
    guard let url = URL(string: urlString) else {
        showInvalidUrlAlert()
        return
    }
    UIApplication.shared.open(url)
}
此示例适用于以下示例:“https://www.google.de/?hl=de”
但是,当传递无效的URL时,这在我的应用程序中也是可能的(例如:“asdfd”),我在控制台上收到此错误,但在应用程序中什么也没有发生:

[默认]无法打开URL asdf:错误域= NSOSStatusErrorDomain代码= -50“无效的输入参数” UserInfo = {NSDebugDescription =无效的输入参数,_LSLine = 252,_LSFunction =-[_ LSDOpenClient openURL:options:completionHandler:]}

最佳做法是什么?

最佳答案

您可能要使用completionHandler参数:

func openURL(_ urlString: String) {
    guard let url = URL(string: urlString) else {
        showInvalidUrlAlert()
        return
    }
    UIApplication.shared.open(url, completionHandler: { success in
        if success {
            print("opened")
        } else {
            print("failed")
            // showInvalidUrlAlert()
        }
    })
}

关于ios - 打开时处理错误URL的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63101116/

相关文章:

ios - Objective-C AVCaptureDevice 前置摄像头

ios - 如何检测是否有任何外部库正在调用 [UIDevice currentDevice] uniqueIdentifier]?

swift - 升级到 swift3 时,出现错误 'cannot override a property with type GKEntity'

swift - (as!SKView?) 和 (as?SKView) 有什么区别

ios - Xcode 6.3.2 中的管理器 - 没有估计二进制大小

iphone - 整个应用程序iphone的 session 管理

swift - 从两个字典中删除非重复键

url - URL 的整个第一部分怎么称呼?

Django url 国际化在生产模式下不起作用

java - 如何从 GWT 应用程序中的 URL 中删除哈希参数