Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL decode in iOS

I am using Swift 1.2 to develop my iPhone application and I am communicating with a http web service.

The response I am getting is in query string format (key-value pairs) and URL encoded in .Net.

I can get the response, but looking the proper way to decode using Swift.

Sample response is as follows

status=1&message=The+transaction+for+GBP+12.50+was+successful 

Tried following way to decode and get the server response

// This provides encoded response String var responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as! String var decodedResponse = responseString.stringByReplacingEscapesUsingEncoding(NSUTF8StringEncoding)! 

How can I replace all URL escaped characters in the string?

like image 502
JibW Avatar asked Oct 06 '15 16:10

JibW


1 Answers

To encode and decode urls create this extention somewhere in the project:

Swift 2.0

extension String {        func encodeUrl() -> String     {         return self.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())     } func decodeUrl() -> String     {         return self.stringByRemovingPercentEncoding     }  } 

Swift 3.0

 extension String     {            func encodeUrl() -> String         {             return self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed())         }     func decodeUrl() -> String         {             return self.removingPercentEncoding         }      } 

Swift 4.1

extension String {     func encodeUrl() -> String?     {         return self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed)     }     func decodeUrl() -> String?     {         return self.removingPercentEncoding     } } 
like image 122
Vyacheslav Avatar answered Oct 12 '22 23:10

Vyacheslav