0

I am developing an app using Swift. In my app, I am getting a value from a UITextField and a UITextView and sending that value as a parameter to a JSON API. I am able to send the value, but when I send the value with white space, my app crashes and shows error as null value. But I need to send the value with space also. For example, getting the full name or address.

Code:

 Alamofire.request(.GET, "https://www.something.com/cid="+MyCustId+"", parameters: nil, encoding: .URL, headers: nil).response { (req, res, data, error) -> Void in
                let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
                print(dataString)

}

Here, MyCustId is the variable which is getting the value from UITextField. Thanks in advance!

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
user7333282
  • 101
  • 1
  • 2
  • 15

2 Answers2

0

You should replace spaces with %20 in the URL by the following method.

func addPercentageToUrl(urlString : String) -> String{

            return urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!
        }


func makeService(){
let url = addPercentageToUrl(urlString : "https://www.something.com/cid="+MyCustId+"")
Alamofire.request(.GET, url, parameters: nil, encoding: .URL, headers: nil).response { (req, res, data, error) -> Void in
                let dataString = NSString(data: data!, encoding:NSUTF8StringEncoding)
                print(dataString)

}
}

Please update you code like this.

Usman Javed
  • 2,437
  • 1
  • 17
  • 26
0

please use stringByAddingPercentEncodingWithAllowedCharacters method for adding space in url

let myStr = strOfUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()
Sunil Prajapati
  • 473
  • 5
  • 17