0

I'm making an app that calls a weather api. As expected in the url request you can't use any character that you want. The app haves a TextField in which you can search the city that you want to have the general weather. Searching something with special characters like: "España" or "México" crashes the App because the url request doesn't accept "ñ" or "é". I already fixed the problem made by putting a blank space in the textField on the firsts lines of the fetch() function. Thanks for the time. Sorry for the band English.

class WeatherClass: ObservableObject {
    @Published var weatherAddress: String = ""
    @Published var weatherDays: [WeatherDays] = []
    @Published var city: String = ""
    var cityTrimmed: String = ""
    
    func fetch() {
        
        city = city.trimmingCharacters(in: [" "])
        for letter in city {
            if letter != " " {
                cityTrimmed.append(letter)
            }
        }
          
        let apiKey = "AP8LUYMSTHFQAF"
        
        let url = URL(string: "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/\(cityTrimmed)?key=\(apiKey)")!
            URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else { return }
                
            if let weather = try? JSONDecoder().decode(WeatherData.self, from: data) {
                DispatchQueue.main.async {
                    self.cityTrimmed.removeAll()
                    self.weatherAddress = weather.resolvedAddress
                    self.weatherDays = weather.days
                }

struct searchBarUI: View {
    @ObservedObject var weatherModel: WeatherClass
    
    var body: some View {
        TextField("Search city", text: $weatherModel.city).frame(height:30).multilineTextAlignment(.center).background().cornerRadius(25).padding(.horizontal)
    }
}
  • 1
    Do you know about "percent encoding"? – matt Nov 23 '22 at 00:52
  • 1
    Also never call `URL(string`. Use URLComponents. It solves these problems neatly. – matt Nov 23 '22 at 00:53
  • @matt I don't know about "percent encoding". Can you give me a example? Sorry, I'm almost new to programmig(3 months), so most of the time I don't know how to solve a problem without an example. – SirEdwardIII Nov 23 '22 at 00:55
  • Googling might help. I found this, which might provide some inspiration: https://stackoverflow.com/a/42029918/341994 – matt Nov 23 '22 at 01:29

0 Answers0