Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put an array into a URLQueryItem?

I'm using Firebase dynamic links and need to put an array of strings into the value of a URLQueryItem and then be able to convert it back into an array when the link is received. How can I do this?

I tried

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

but this resolves to the error: "Cannot convert value of type '[String]?' to expected argument type 'String?'".

When I'm handling opening this URLQueryItem, how do I handle an array? I'll be able to extract the value of the query item in the below way, but how can I convert that back to an array of strings?

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?
    }
}
like image 350
nickcoding2 Avatar asked Feb 05 '26 05:02

nickcoding2


1 Answers

The way I would build a URL with an array of values would be:

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
}

And the way I would parse a URL would be

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

Now, whether you use the key[] syntax (with the []), or just key (without the []) is up to you. See https://stackoverflow.com/a/30400578/1271826. But the idea is the same, either way, that you repeat the key name in the URL for each value in the array, rather than key=[value1,value2] or anything like that.

like image 116
Rob Avatar answered Feb 06 '26 21:02

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!