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)
}
}