简体   繁体   English

Swift:字符串url编码无法按预期工作

[英]Swift: string url encoding not working as expected

So I have a url like this: 所以我有一个这样的网址:

let remoetURL = "http://xxx-test.img-cn-hangzhou.aliyuncs.com/materials/talk_-XXXXX-XXXXXXX/STEM RULE.pdf"

As you can see, at then end of the url, there is a white space, so I need to get rid of it to have a valid encoded url. 正如你所看到的,在url的末尾,有一个空格,所以我需要摆脱它以获得一个有效的编码网址。

After doing some research, I realized I might use 做了一些研究后,我意识到我可能会用

let escapedString = remoteURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet())

But this does not returned the expected working url, because it encodes the ":" after "http" too 但是这并没有返回预期的工作URL,因为它也在“http”之后编码“:”

http%3A//xiaobandeng-staging.img-cn-hangzhou.aliyuncs.com/talk_materials/talk_-K4yjX4-238Ku74WVIJk/STEM%20RULE.pdf

I have also tried URLHostAllowedCharacterSet, but no luck. 我也试过了URLHostAllowedCharacterSet,但没有运气。 So I wonder if it is because I don't have www here, so it does not recognise which part is the host correctly. 所以我想知道是不是因为我这里没有www ,所以它无法正确识别哪个部分是主机。 If so, what might be the elegant solution? 如果是这样,那么优雅的解决方案是什么? I know I could replace white spaces with %20 by calling stringByReplacingOccurrencesOfString, but that seems just a bit fragile. 我知道我可以通过调用stringByReplacingOccurrencesOfString来替换%20的空格,但这似乎有点脆弱。

Thank you in advance. 先感谢您。

Try this used by SwiftyJSON 尝试使用SwiftyJSON

let urlString = remoteURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

Swift 3 : 斯威夫特3

let urlString = remoteURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

Have you try this 你试试这个吗?

let urlPath = NSString(format: remoetURL).stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

For iOS 9 适用于iOS 9

let encodedHost = NSString(format: remoetURL).stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())

Hope this will help you 希望这个能对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM