ios URL(字符串:)始终不起作用 [英] ios URL(string: ) not working always
问题描述
let testurl = "http://akns-
images.eonline.com/eol_images/Entire_Site/2018029/rs_1024x759-
180129200032-1024.lupita-nyongo-angela-bassett-black-panther-
premiere.ct.012918.jpg?fit=inside|900:auto"
if let url = URL(string: testurl){
print("valid")
}else {
print("invalid")
}
这会打印为无效的网址。但是在Web浏览器中显示图像。我已经看到很多方法,但是它会抛出Apple警告,使用 stringByAddingPercentEncodingWithAllowedCharacters
,这不会一直有效。
This prints as an invalid URL. But shows the image in web browser. I have seen lot of methods but it throws Apple warning to use stringByAddingPercentEncodingWithAllowedCharacters
and this doesn't work always.
我更喜欢一个解决方案来清理网址而不编码完整的urlstring。在初始步骤对其进行编码可能是一个摩擦,当传递到外部库时,将重新编码url并使其无效。
I would prefer a solution to clean-up the url without encoding the complete urlstring. Encoding it at initial step can be a friction when passing to external libraries which will re-encode the url and make it invalid.
推荐答案
我想我找到了答案。仍将检查是否有任何副作用,欢迎提出意见:
I think I have found my answer. Still will be checking for any side effects, comments are welcome:
let urlst = "http://akns-
images.eonline.com/eol_images/Entire_Site/2018029/rs_1024x759-
180129200032-1024.lupita-nyongo-angela-bassett-black-panther-
premiere.ct.012918.jpg?fit=inside|900:auto"
extension String {
func getCleanedURL() -> URL? {
guard self.isEmpty == false else {
return nil
}
if let url = URL(string: self) {
return url
} else {
if let urlEscapedString = self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) , let escapedURL = URL(string: urlEscapedString){
return escapedURL
}
}
return nil
}
}
这不会对完整的URL进行编码但只编码无效的查询字符(例如url中的'|')。因此,它仍然可以作为字符串或有效URL传递。
This does not encode the complete URL but encodes only the invalid query characters (in eg url its '|'). Thus it can still be passed around as a string or a valid URL.
这篇关于ios URL(字符串:)始终不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!