2016-11-15 90 views
2

我想在swift 3中構造一個url,但我不明白爲什麼它不會將字符串附加到baseURL正確的輸出不是我所期望的。在swift 2中,它工作正常。如何在swift 3中使用URL構造url(string:,relativeTo :)

let token = "12token34" 

let baseURL = URL(string: "https://api.mysite.net/map/\(token)/") 

let desiredURL = URL(string: "37.8267,-122.4233", relativeTo: baseURL as URL?) 

結果

37.8267,-122.4233 -- https://api.mysite.net/map/12token34/ 

我期待下面:

https://api.mysite.net/map/12token34/37.8267,-122.4233 
+1

你的方法,它正在它只是不會打印像您期望 –

+1

試'print(desiredURL?.absoluteString)' –

+1

注意:不需要將URL轉換爲URL? –

回答

1
let token = "12token34" 
let baseURL = URL(string: "https://api.mysite.net/map/\(token)/") 
let desiredURL = URL(string: "37.8267,-122.4233", relativeTo: baseURL as URL?) 

這是錯誤的原因:

/// Initialize with string, relative to another URL. 
/// 
/// Returns `nil` if a `URL` cannot be formed with the string (for example, if the string contains characters that are illegal in a URL, or is an empty string). 
public init?(string: String, relativeTo url: URL?) 

所以,如果你想添加的url,輸出應該是這樣的:

let output = URL(string: baseURL!.absoluteString) 
output?.appendingPathComponent("37.8267,-122.4233") 

這樣你就可以直接使用:

baseURL!.appendingPathComponent("37.8267,-122.4233") 
+0

,我已經用於打印操場,實際答案是最後一行。 –