Replacing space for URL in swift4

I have problem replacing the space in URL. I'm trying to build a weather app for my class. I have textField for the user to submit a place but for the URL link the space is actually "%20". I don't know how to find the space in the textField and replace it with "%20". (I'm a beginner in Swift)

@IBAction func locationSearchButton(_ sender: Any) {
    nameLabel.text = (nameTextField.text)?.capitalized

    let text: String = nameTextField.text!

    getWeatherData(city: text)

    //if the user put "new york" I want to replace the space with "%20"
   // return text should be "new%20york"

func getWeatherData(city: String) {
  let url = "\(city)&units=imperial&appid=1234567890"

  Alamofire.request(url).validate().responseJSON { response in
        switch response.result {
        case .success:
            print("Get weather Successful")

            if let json = response.result.value {
                let weather = Weather(JSON: json as! [String:Any])
                print(weather?.name as Any)
                //                    print(weather?.temperature as Any)
        case .failure(let error):

1 answer

  • answered 2018-05-16 05:54 Pratik Prajapati

    Try this :

    let url = "\(city)&units=imperial&appid=1234567890"
    let escapedString = url.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
    if let finalUrl = URL(string: escapedString) {
        // call your api function here