如何在 iOS 中不指定 HTTP 或 HTTPS 的情况下打开 URL?
问题描述:
在我的 iOS 应用中,我使用以下代码打开链接:
In my iOS app I am opening links using the code below:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",myurl]]];
链接是动态的,不提供 HTTP/HTTPS.
The links come dynamically and HTTP/HTTPS is not provided.
我无法对 HTTP 或 HTTPS 进行硬编码,因为我不知道该 URL 是否包含 HTTP 或 HTTPS.如何在不指定 HTTP 或 HTTPS 的情况下打开 URL?
I cannot hardcode HTTP or HTTPS because I don't know if the URL has HTTP or HTTPS. How can I open a URL without specifying HTTP or HTTPS?
答
Swift 的单线解决方案:
One-liner solution for Swift:
let urlString = "example.com"
let validUrlString = dataText.hasPrefix("http") ? urlString : "http://\(urlString)"