在我的 iOS 应用程序中,我使用以下代码打开链接:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",myurl]]];
Run Code Online (Sandbox Code Playgroud)
链接是动态的,不提供 HTTP/HTTPS。
我无法对 HTTP 或 HTTPS 进行硬编码,因为我不知道 URL 是否具有 HTTP 或 HTTPS。如何在不指定 HTTP 或 HTTPS 的情况下打开 URL?
我认为这是比此处介绍的方法更好的方法,因为它避免了字符串比较和操作。
public extension URL {
var sanitise: URL {
if var components = URLComponents(url: self, resolvingAgainstBaseURL: false) {
if components.scheme == nil {
components.scheme = "http"
}
return components.url ?? self
}
return self
}
}
Run Code Online (Sandbox Code Playgroud)
Swift 的单线解决方案:
let urlString = "example.com"
let validUrlString = dataText.hasPrefix("http") ? urlString : "http://\(urlString)"
Run Code Online (Sandbox Code Playgroud)
谁说你不知道url是否包含http?你可以发现...
写在prefixheader.pch
下面。
#define contains(str1, str2) ([str1 rangeOfString: str2 ].location != NSNotFound)
Run Code Online (Sandbox Code Playgroud)
然后在你的 .m 中写下。
if (!contains(myurl, "http")) {
myurl = [NSString stringWithFormat:@"http://%@", myurl];
}
Run Code Online (Sandbox Code Playgroud)
你完成了!
需要帮助请叫我。
归档时间: |
|
查看次数: |
4863 次 |
最近记录: |