在Swift3中将查询参数添加到iOS中的GET URL

时间:2017-08-03 05:56:25

标签: ios swift3 get xcode8

我有一个带

的网址

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

它基本上是一个GET网址,因此我需要传递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!

我做对了还是其他任何修改?请告诉。

3 个答案:

答案 0 :(得分:3)

除非你有子NSURLQueryItem,否则你的init方法不正确。对于NSURLQueryItem,每Apple's documentation,init方法签名为:

init(name: String, value: String?)

这意味着您的查询项应该像这样创建:

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

这将以您期望的格式正确地将它们添加到网址。

答案 1 :(得分: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)!
    }

答案 2 :(得分:1)

您可以使用String

尝试其他方法
let baseUrlString = "https://api.asiancar.com/api/"
let timeStamp = 1234568878788998989
let isMobile = true
let settingsUrlString = "\(baseUrlString)applicationsettings?timestamp=\(timeStamp)&isMobile=\(isMobile)"
print(settingsUrlString)
let url = URL(string: settingsUrlString)

输出:https://api.asiancar.com/api/applicationsettings?timestamp=1234568878788998989&isMobile=true