我是 IOS 開發的新手,最近在網上學習了一門課程。對于一個 fetchWeather(cityName: String) 函式,我試圖通過一個字串創建一個 URL,該字串具有天氣預報網站的名稱、我的 API 密鑰和城市名稱。但是,我發現如果我使用cityNamefrom 函式,URL 會失敗。連線的事情是,如果我不使用引數值,而是city_name在函式中創建一個與 具有相同值的新區域變數cityName,即引數值,則 URL 成功。這是我的兩個測驗用例:
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")
}
這是輸出:
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
這兩個 url_strings 看起來完全一樣,那么為什么它們不同呢?我相信這兩個 url_strings 之間的區別在于我的第一個 URL 失敗而第二個 URL 成功的問題。
uj5u.com熱心網友回復:
實際將您的確切輸出剪切并粘貼到您的問題中做得很好。我就是這樣診斷的。
cityName你要傳遞的最后fetchWeather有一個U 0020 SPACE。
00000000 4c 6f 6e 64 6f 6e 20 |London |
00000007
URL 決議器不喜歡這樣。試試這個:
let first_urlString = weatherURL cityName.trimmingCharacters(in: .whitespacesAndNewlines)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/478176.html
上一篇:使用LINQ選擇.NETFramework中的最后一條記錄
下一篇:在html中重用部分url的內容
