How to encode special character like ’ (NSWindowsCP1250StringEncoding) in Swift2

孤人 提交于 2019-12-11 11:57:20

问题


As in Swift2 stringByAddingPercentEscapesUsingEncoding() is deprecated instead of stringByAddingPercentEncodingWithAllowedCharacters() is used.

But how to encode the especial character like ' % & in swift2

For example in iOS8(swift1.2) i used following code for encoding

NSURL(string: "myurl.php?deviceName=name’phone".stringByAddingPercentEscapesUsingEncoding(NSWindowsCP1250StringEncoding)!)

it work fine i.e. on server it decode correctly.

But in iOS9(Swift2.0) i used following code

NSURL(string: "myurl.php?deviceName=name ’phone".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())!)

It will not decode properly.
please tell me how i can encode special charater in swift2.0 ?

EDIT : Eric D answer is right but when i encode below stringURL it will not encode properly. Why?

let stringURL = "https://my.server.com/login.php?e=email&dn=my’s iPad&d=5&er=D550772E-34BB-4DCB-89C9-E746FAD83D24&tz=330"
        print(stringURL)
        let charSet = NSCharacterSet.URLPathAllowedCharacterSet()
        let encoded = stringURL.stringByAddingPercentEncodingWithAllowedCharacters(charSet)!

        let url = NSURL(string: encoded.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet())!)!

        print(url) //https%253A//my.server.com/login.php%253Fe=email&dn=my%25E2%2580%2599s%2520iPad&d=5&er=D550772E-34BB-4DCB-89C9-E746FAD83D ... 4&tz=330

EDIT 2:

How to encode NSWindowsCP1250StringEncoding in swift2.0 ?


回答1:


Use URLPathAllowedCharacterSet() as character set:

let stringURL = "myurl.php?deviceName=name'phone"
let charSet = NSCharacterSet.URLPathAllowedCharacterSet()
let encoded = stringURL.stringByAddingPercentEncodingWithAllowedCharacters(charSet)!
let url = NSURL(string: encoded)!

print(url)  // "myurl.php%3FdeviceName=name'phone"

Note that ' doesn't have to be encoded, it's a valid URL character.

Update: in the comments you state that it's still not working because your encoded URL is truncated and contains ..., but actually this is likely to be just a printed description truncated by NSURL; the actual URL contained by the NSURL object should be ok. Otherwise it would be nil. You should check on your server side for problems with very long but correct URLs.




回答2:


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


来源:https://stackoverflow.com/questions/32631199/how-to-encode-special-character-like-nswindowscp1250stringencoding-in-swift2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!