问题描述
作为 API 调用的一部分,我收到了随机 URL。所以我不知道我得到了什么。
我想用它做两件事。
- 格式化并在标签中显示
NSTextField(labelWithString:)
- 允许用户使用
NSWorkspace.shared.open(_:)
在浏览器(Safari 或他们首选的浏览器)中打开它
我总是强制解包 URL 结构,因为我个人发现它永远不会失败,我做了一些测试,虽然不严格。
我想将 URL 格式化为这样的格式。
-
https://www.google.co.uk
->google.co.uk
-
https://en.wikipedia.org/wiki/%22Hello,_World!%22_program
->en.wikipedia.org
-
https://blog.toyota.co.uk/toyota-production-system-glossary
->toyota.co.uk
依此类推,您就大致了解了。
我曾经做过这样的事情。
let google = "https://www.google.co.uk"
let googleURL = URL(string: "https://www.google.co.uk")!
let formattedGoogleURL = googleURL.host!
print(formattedGoogleURL)
// prints www.google.co.uk
我遇到了这个扩展。
extension URL {
var formatted: String {
(host ?? "").replacingOccurrences(of: "www.",with: "")
}
}
结果产生。
// Let's try with the extension instance property
print(googleURL.formatted)
// prints google.co.uk
有一天,我在 API 调用中收到了这个 URL。
https://divinations.substack.com/p/linkedins-alternate-universe##
它使我的应用程序崩溃。我尝试在 Safari 中打开它,它打开得很好。那么为什么 URL 结构会为它返回 nil 呢?我假设如果它在 Safari 中打开,那么它不应该为 URL 结构返回 nil。
let linkedIn = "https://divinations.substack.com/p/linkedins-alternate-universe##"
let linkedInURL = URL(string: "https://divinations.substack.com/p/linkedins-alternate-universe##")
print(linkedInURL)
// prints nil
我发现是因为##
。
let modifiedLinkedInString = "https://divinations.substack.com/p/linkedins-alternate-universe"
let modifiedLinkedInURL = URL(string: "https://divinations.substack.com/p/linkedins-alternate-universe")
print(modifiedLinkedInURL)
// prints Optional(https://divinations.substack.com/p/linkedins-alternate-universe)
// the culprit is ##
这件事教会我基本上永远不要强制解包 URL 结构,因为有些 URL 会返回 nil。
我将扩展修改成了这个。
extension URL {
var formatted: String {
(host ?? "").replacingOccurrences(of: "www.",with: "").trimmingCharacters(in: CharacterSet.urlPathAllowed.inverted)
}
}
因此...
// Force unwrap the URL struct because the extension property will take care of illegal characters
print(modifiedLinkedInURL!.formatted)
// prints divinations.substack.com
所以这看起来不错,所以我以为我已经完蛋了。
有一天,作为 API 调用的一部分,我遇到了这个 URL,https://en.wikipedia.org/wiki/Leary–Lettvin_debate
let wikipedia = "https://en.wikipedia.org/wiki/Leary–Lettvin_debate"
let wikipediaURL = URL(string: "https://en.wikipedia.org/wiki/Leary–Lettvin_debate")
print(wikipediaURL!.formatted)
// crashed my app
print(wikipediaURL)
// prints nil
我的扩展程序不起作用。维基百科 URL 在 Safari 中运行良好,我不知道该怎么做。如何确保我的应用永远不会因为神秘的 URL 规则而崩溃?
必须有一种方法来格式化网址而不会让您的应用程序崩溃,并且能够使用 NSWorkspace.shared.open(_:)
打开它。
如果它在 Safari 中打开,那么它应该可以在我的应用中运行。我无法控制 API 数据。我现在必须处理神秘的 URL 规则,否则它通常可以正常工作。我永远不会因为两起事件而强行打开包装,我对我处理它的方式抱有更多期望。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)