Split URL query in Swift

2020-04-27 02:02发布

I have the following URL query:

encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN

How can I split the query to get the of encodedMessage and signature values?

标签: swift url
2条回答
趁早两清
2楼-- · 2020-04-27 02:13

The right way to achieve this is to work with URLComponents:

A structure designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts.

By getting the url components host string and query​Items array, as follows:

if let urlComponents = URLComponents(string: "http://mydummysite.com?encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"), let host = urlComponents.host, let queryItems = urlComponents.queryItems {

    print(host) // mydummysite.com

    print(queryItems) // [encodedMessage=PD94bWwgdmVyNlPg==, signature=kcig33sdAOAr/YYGf5r4HGN]
}

queryItems array contains URLQuery​Item objects, which have name and value properties:

if let urlComponents = URLComponents(string: "http://mydummysite.com?encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"),let queryItems = urlComponents.queryItems {

    // for example, we will get the first item name and value:
    let name = queryItems[0].name // encodedMessage
    let value = queryItems[0].value // PD94bWwgdmVyNlPg==
}

Also:

In case of you are getting the query without the full url, I'd suggest to do a pretty simple trick, by adding a dummy host as a prefix to your query string, as follows:

let myQuery = "encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"
let myDummyUrlString = "http://stackoverflow.com?" + myQuery

if let urlComponents = URLComponents(string: myDummyUrlString),let queryItems = urlComponents.queryItems {
    // for example, we will get the first item name and value:
    let name = queryItems[0].name // encodedMessage
    let value = queryItems[0].value // PD94bWwgdmVyNlPg==
} else {
    print("invalid url")
}
查看更多
Fickle 薄情
3楼-- · 2020-04-27 02:32

You can get the key value pairs this way:

let str = "encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"
let arr = str.components(separatedBy:"&")
var data = [String:Any]()
for row in arr {
    let pairs = row.components(separatedBy:"=")
    data[pairs[0]] = pairs[1]
}
let message = data["encodedMessage"]
let sig = data["signature"]

I am not sure if that's what you were looking for or not. If it is not, could you please clarify a bit further as to what you are looking for?

查看更多
登录 后发表回答