2017-08-03 73 views
2

在iOS中獲取URL我有添加查詢參數在Swift3

https://api.asiancar.com/api/applicationsettings

的URL它基本上是一個GET URL,所以我需要傳遞一個boolean「isMobile」和timestamp作爲查詢參數。如何實現這一目標作爲傳遞查詢後,最終的URL看起來像這樣:

https://api.asiancar.com/api/applicationsettings?timestamp=111122244556789879&isMobile=true

let queryItems = [ 
    NSURLQueryItem(timestamp: "1234568878788998989", isMobile: true), 
    NSURLQueryItem(timestamp: "1234568878788998989", isMobile: true) 
] 
let urlComps = NSURLComponents(string: "www.api.asiancar.com/api/applicationsettings")! 
urlComps.queryItems = queryItems 
let URL = urlComps.URL! 

我做正確的或任何其他修改?請告訴。

+0

您可以先創建網址的字符串,然後使用'讓URL = URL(字符串:「」)'創建最終的URL。 – Akhilrajtr

+0

請發佈答案 –

+0

儘管接受的答案在技術上會起作用,但我強烈建議您查看我的答案並繼續使用url組件。一旦習慣了它們,它們更加靈活並且不易出錯 – BJHStudios

回答

3

除非你有子類NSURLQueryItem,那麼你的init方法是不正確的。每Apple's documentationNSURLQueryItem,init方法的簽名是:

init(name: String, value: String?) 

這意味着你的查詢項目應該這樣創建:

let queryItems = [NSURLQueryItem(name: "timestamp" value: "1234568878788998989"), NSURLQueryItem(name: "isMobile", value: "true")] 

這將正常它們添加到格式的URL你期待。

1

試試這個:

let API_PREFIX = "www.api.asiancar.com/api/applicationsettings" 

var url : URL? = URL.init(string: API_PREFIX + queryItems(dictionary: [name: "isMobile", value: "true"] as [String : Any])) 

func queryItems(dictionary: [String:Any]) -> String { 
     var components = URLComponents() 
     print(components.url!) 
     components.queryItems = dictionary.map { 
      URLQueryItem(name: $0, value: $1 as String) 
     } 
     return (components.url?.absoluteString)! 
    }