0

What's the most concise way to encode URL in Swift?

I have

let request_url = URL(string:"http://api.openweathermap.org/data/2.5/weather?appid=dca0aa44807a0bc05ed51c6a85472341&q="+"New York")

How can i add + instead of a space between New and York through some simple method available in swift?

Wkhan
  • 95
  • 3
  • 11
  • `replacingOccurrences(of:with:)`? – Sweeper Mar 23 '20 at 13:47
  • Does this answer your question? [Swift - encode URL](https://stackoverflow.com/questions/24551816/swift-encode-url) – heyfrank Mar 23 '20 at 13:51
  • yes. We can do string manipulation. But how can we use some method to automatically do this for us? + sign was just an example. We have other things in the URL as well.Can we do this through some URL builder? – Wkhan Mar 23 '20 at 13:52
  • @fl034 No It doesn't help. I need a simple method Which takes a string URL and converts it into a formatted URL (for example Adding + sign instead of spaces) – Wkhan Mar 23 '20 at 13:55

1 Answers1

0

If I understand you correctly, you want to encode spaces as + and encode other special characters correctly as well. So this approach uses the native function addingPercentEncoding(withAllowedCharacters:) that translates a sspaces to %20. Afterwards we replace all occurrences of %20 with a +.

extension URL {
    init?(encoding string: String) {
        let encodedString = string
            .addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)                
            .replacingOccurrences(of: "%20", with: "+")                
        guard let encodedString != nil else { return nil }
        self.init(string: encodedString!)
    }
}

This is encapsulated in an URL init function, so you can use it like this:

let requestUrl = URL(encoding: "http://api.openweathermap.org/data/2.5/weather?appid=dca0aa44807a0bc05ed51c6a85472341&q="+"New York")
heyfrank
  • 5,291
  • 3
  • 32
  • 46