I am a newbie in IOS development and recently take one course online. For one fetchWeather(cityName: String) function, I am trying to create an URL by a string that has the name of a weather forecast website, my API key and the city name. However, I find that if I use the cityName
from the function, the URL fails. The wired thing is if I do not use the argument value, but create a new local variable city_name
in the function that has the same value with cityName
, which is the argument value, the URL succeed. Here are my two test cases:
func fetchWeather(cityName: String) {
// The first case that use the argument of the function
print("First test case: ")
print(cityName)
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?appid=2b5e3c1ae10223238e8bbf73b814e563&units=metric&q="
let first_urlString = weatherURL cityName
guard let first_url = URL(string:first_urlString) else{
print("First_URL fails")
// The second case that directly combine two strings
print("\nSecond test case: ")
let city_name = "London"
let second_url_String = weatherURL city_name
guard let second_url = URL(string:second_url_String) else{
print("Second_URL fails")
return
}
print("Second_URL succeed")
print("\n" first_urlString)
print(second_url_String)
print("The first string is equals to the second string: " String(first_urlString==second_url_String))
return
}
print("First_URL succeed")
}
And here's the output:
First test case:
London
First_URL fails
Second test case:
Second_URL succeed
https://api.openweathermap.org/data/2.5/weather?appid=2b5e3c1ae10223238e8bbf73b814e563&units=metric&q=London
https://api.openweathermap.org/data/2.5/weather?appid=2b5e3c1ae10223238e8bbf73b814e563&units=metric&q=London
The first string is equals to the second string: false
Those two url_strings look exactly the same, so why they are different? I believe that the difference between those two url_strings is the problem that my first URL fails and the second one succeed.
CodePudding user response:
Good job actually cutting and pasting your exact output into your question. That's how I was able to diagnose this.
The cityName
you're passing to fetchWeather
has a U 0020 SPACE at the end.
00000000 4c 6f 6e 64 6f 6e 20 |London |
00000007
The URL parser doesn't like that. Try this instead:
let first_urlString = weatherURL cityName.trimmingCharacters(in: .whitespacesAndNewlines)