如何将数组放入URLQueryItem?

问题描述 投票:0回答:2

我正在使用 Firebase 动态链接,需要将字符串数组放入 URLQueryItem 的值中,然后在收到链接时能够将其转换回数组。我该怎么做?

我试过了

let queryItem = URLQueryItem(name: "array", value: ["item 1", "item 2", "item 3"])

但这解决了错误:“无法转换'[String]类型的值?'到预期的参数类型“字符串?””。

当我处理打开此 URLQueryItem 时,如何处理数组?我将能够通过以下方式提取查询项的值,但是如何将其转换回字符串数组?

let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
let queryItems = components.queryItems
for queryItem in queryItems {
    if queryItem.name == "array" {
        let unwrappedStringifiedArray = queryItem.value ?? []
        //what do I do with the unwrapped stringified array here?
    }
}
arrays swift firebase casting firebase-dynamic-links
2个回答
0
投票

我使用值数组构建 URL 的方法是:

func buildURL() -> URL? {
    let url = URL(string: "https://...")!
    var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!

    let values = ["item 1", "item 2", "item 3"]
    components.queryItems = values.map { URLQueryItem(name: "array[]", value: $0) }

    return components.url
}

我解析 URL 的方式是

func parse(url: URL) -> [String]? {
    URLComponents(url: url, resolvingAgainstBaseURL: false)?
        .queryItems?
        .filter { $0.name == "array[]" }
        .compactMap { $0.value }
}

现在,您可以选择使用

key[]
语法(带有
[]
),还是仅使用
key
(不带
[]
)。请参阅https://stackoverflow.com/a/30400578/1271826。但无论哪种方式,想法都是相同的,即为数组中的每个值重复 URL 中的键名称,而不是
key=[value1,value2]
或类似的内容。


0
投票
let dictionary = { 
    "array": ["value0", "value1"]
}

如果您需要数组密钥

https://baseurl.com?array[0]=value0&array[1]=value1
功能会是这样的

func queryItems(dictionary: [String: Any]) -> [URLQueryItem] {
    let dictlist = dictionary.map { $0 }
    var queryList: [URLQueryItem] = []
    
    for dict in dictlist {
        if let array = dict.value as? [String] {
            for index in 0...array.count - 1 {
                queryList.append(URLQueryItem(name: "\(dict.key)[\(index)]", value: array[index].replacingOccurrences(of: " ", with: "%20")))
            }
        } else {
            queryList.append(URLQueryItem(name: dict.key, value: (dict.value as? LosslessStringConvertible)?.description))
        }
    }
    return queryList
}

如果您需要数组键

https://baseurl.com?array[]=value0&array[]=value1
,您可以删除函数上的
index
。会是这样的

func queryItems(dictionary: [String: Any]) -> [URLQueryItem] {
    let dictlist = dictionary.map { $0 }
    var queryList: [URLQueryItem] = []
    
    for dict in dictlist {
        if let array = dict.value as? [String] {
            for index in 0...array.count - 1 {
                queryList.append(URLQueryItem(name: "\(dict.key)[]", value: array[index].replacingOccurrences(of: " ", with: "%20")))
            }
        } else {
            queryList.append(URLQueryItem(name: dict.key, value: (dict.value as? LosslessStringConvertible)?.description))
        }
    }
    return queryList
}
© www.soinside.com 2019 - 2024. All rights reserved.