Zizoo Zizoo - 11 months ago 47
iOS Question

How to send litter '&' as url parameter - swift

I have a code to update name of department in the database .. I use this encoding code :

let myurlstring="http:example/updateDepartment.php?deptName="+"\(deptName)"+"&id="+"\(deptID)"

let escapedString = myurlstring.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)

let myUrl = URL(string:escapedString!)!

It works very well , but when
string contains this litter
it's not working.

example1 : send request with
deptName = "CIT and Network"
it will work .

example2 : send request with
deptName = "CIT & Network"
will be in the database as only "CIT" any litter after
will be skipped.

any help ?

Answer Source

Use URLComponents + URLQueryItem instead. It can be used to encode the query part from structured input:

var comp = URLComponents(string: "http://example.com")!
comp.path = "/some path to/update.php"
comp.queryItems = [
    URLQueryItem(name: "deptName", value: "CIT & Network"),
    URLQueryItem(name: "id", value: "123456"),

let url = comp.url!
// http://example.com/some%20path%20to/update.php?deptName=CIT%20%26%20Network&id=123456