Rizwan Shaikh
Rizwan Shaikh

Reputation: 2904

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

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 ?

Upvotes: 1

Views: 1393

Answers (2)

raja
raja

Reputation: 1161

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

Upvotes: 0

Eric Aya
Eric Aya

Reputation: 70098

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.

Upvotes: 1

Related Questions