Chenglu
Chenglu

Reputation: 884

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.

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

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. So I wonder if it is because I don't have www here, so it does not recognise which part is the host correctly. 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.

Thank you in advance.

Upvotes: 4

Views: 6958

Answers (2)

Dhaval Parmar
Dhaval Parmar

Reputation: 18978

Try this used by SwiftyJSON

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

Swift 3:

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

Upvotes: 9

Nirav D
Nirav D

Reputation: 72460

Have you try this

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

For iOS 9

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

Hope this will help you

Upvotes: 0

Related Questions