Best way to parse URL string to get values for keys?

前端 未结 16 1047
广开言路
广开言路 2020-11-29 18:36

I need to parse a URL string like this one:

&ad_eurl=http://www.youtube.com/video/4bL4FI1Gz6s&hl=it_IT&iv_logging_level=3&ad_flags=0&ends         


        
16条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 19:18

    I also answered this at https://stackoverflow.com/a/26406478/215748.

    You can use queryItems in URLComponents.

    When you get this property’s value, the NSURLComponents class parses the query string and returns an array of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string.

    let url = "http://example.com?param1=value1¶m2=param2"
    let queryItems = URLComponents(string: url)?.queryItems
    let param1 = queryItems?.filter({$0.name == "param1"}).first
    print(param1?.value)
    

    Alternatively, you can add an extension on URL to make things easier.

    extension URL {
        var queryParameters: QueryParameters { return QueryParameters(url: self) }
    }
    
    class QueryParameters {
        let queryItems: [URLQueryItem]
        init(url: URL?) {
            queryItems = URLComponents(string: url?.absoluteString ?? "")?.queryItems ?? []
            print(queryItems)
        }
        subscript(name: String) -> String? {
            return queryItems.first(where: { $0.name == name })?.value
        }
    }
    

    You can then access the parameter by its name.

    let url = URL(string: "http://example.com?param1=value1¶m2=param2")!
    print(url.queryParameters["param1"])
    

提交回复
热议问题