Post

常见URL参数提取及设置

前言

经常在项目中要提取url里的参数,尤其是url里包含了子url这种类型提取比较麻烦,特整理下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
public class UrlTool {
    public static func test() {
        let path1 = "http://www.appleX.com/info?name=balana&age=18" // 简单的标准url
        let path2 = "http://www.appleX.com/info?name=balana&age=18&callback=http://www.googleY.com&type=friend" // 子url在中间
        let path3 = "http://xx/aa?year=123&q1=https://xxx.yy/a?aa1=b&aa2=c&q2=fly://aa/b?d=dd&d2=ddd" // 子url在后面,且子url也自带自己的参数
        let path4 = "http://xx/aa?b=123&q1=https://xxx.yy/a?aa1=b&aa2=c&xx=wx://a&x=1&y=2&q2=sky://aa/b?d=dd&d2=ddd" // 子url与父参数混杂
        let param1 = UrlTool.urlParams(path1)
        let param2 = UrlTool.urlParams(path2)
        let param3 = UrlTool.urlParams(path3)
        let param4 = UrlTool.urlParams(path4)
        print(path1)
        print(param1)
        print(path2)
        print(param2)
        print(path3)
        print(param3)
        print(path4)
        print(param4)
    }
    public static func urlParams(url: URL?) -> [String: String] {
        guard let urlStr = url?.absoluteString, urlStr.count > 0 else {
            return [:]
        }
        return UrlTool.urlParams(urlStr)
    }
    // MARK: 提取URL里的全部参数
    public static func urlParams(_ urlStr: String?) -> [String: String] {
        // "http://www.appleX.com/info?name=balana&age=18" // 简单的标准url
        // "http://www.appleX.com/info?name=balana&age=18&callback=http://www.googleY.com&type=friend" // 子url在中间
        // "http://xx/aa?year=123&q1=https://xxx.yy/a?aa1=b&aa2=c&q2=fly://aa/b?d=dd&d2=ddd" // 子url在后面,且子url也自带自己的参数
        // "http://xx/aa?b=123&q1=https://xxx.yy/a?aa1=b&aa2=c&xx=wechat://a&x=1&y=2&q2=sky://aa/b?d=dd&d2=ddd" // 子url与父参数混杂
        guard let urlStr = urlStr, urlStr.count > 0 else {
            return [:]
        }
        // 找出字url,以及跟子url混杂在一起的参数,以及主url
        let (changeUrl, subDict) = UrlTool.subUrlList(urlStr: urlStr)
        // 防止一个url里有多个子url,所以要按scheme进行拆分,
        let findDict = UrlTool.mainUrlParams(urlStr: changeUrl)
        var fullDict: [String: String] = [:]
        for (key, val) in subDict {
            fullDict[key] = val
        }
        for (key, val) in findDict {
            fullDict[key] = val
        }
        return fullDict
    }
    // MARK: - 找出子URL的列表
    private static func subUrlList(urlStr: String) -> (String, [String: String]) {
        var paramStr = urlStr
        var pramsDict = [String: String]()
        // http://xx/aa?b=123&q1=https://xxx.yy/a?aa1=b&aa2=c&q2=okt://aa/b?d=dd&d2=ddd
        // 防止一个url里有多个子url,所以要按scheme进行拆分,
        let urlStrList = urlStr.components(separatedBy: "://")
        let urlStrListCount = urlStrList.count
        if urlStrListCount > 2 {
            var paramsStrList: [(String,String)] = []
            // 下一个的key在上一个的末尾,?xx=, &xx=xx, xxx
            var nextScheme = ""
            var nextKey = ""
            for idx in (0..<urlStrListCount) {
                let str = urlStrList[idx]
                if idx == 0 {
                    // 第一个
                    nextKey = ""
                    nextScheme = str
                    continue
                } else if idx == (urlStrListCount - 1) {
                    // 最后一个
                    let fullStr = "\(nextScheme)://\(str)"
                    paramsStrList.append((nextKey, fullStr))
                    nextKey = ""
                    nextScheme = ""
                } else {
                   let (findUrl, key, scheme) = UrlTool.realFindSubUrlKeyAndScheme(str: str)
                   let fullStr = "\(nextScheme)://\(findUrl)"
                   paramsStrList.append((nextKey, fullStr))
                   nextKey = key
                   nextScheme = scheme
                }
            }
            // 修改地址
            let findCount = paramsStrList.count
            for idx in (0..<findCount) {
                let (key, url) = paramsStrList[idx]
                if idx == 0 {
                    paramStr = url
                } else {
                    // 需要对url检查参数拆分
                    // http://www.baidu.com/page?name=aa&age=bb
                    // http://www.baidu.com/page&name=aa&age=bb --- 没有?的,后面的参数属于父级的
                    if url.contains("?") == false,
                       url.contains("&"),
                       url.contains("=") {
                        // 存在父类的参数
                        let urlWithSuperParamList = url.components(separatedBy: "&")
                        for (idx, urlItem) in urlWithSuperParamList.enumerated() {
                            if idx == 0 {
                                pramsDict[key] = urlItem
                            } else {
                                let kvList = urlItem.components(separatedBy: "=")
                                if kvList.count == 2 {
                                    let paramKey = kvList[0]
                                    let paramVal = kvList[1]
                                    pramsDict[paramKey] = paramVal
                                }
                            }
                        }
                    } else {
                        pramsDict[key] = url
                    }
                    
                }
            }
        }
        return (paramStr, pramsDict)
    }
    // 通过scheme的标志前一个子url的内容,以及后一个子url的key和scheme
    private static func realFindSubUrlKeyAndScheme(str: String) -> (String, String, String) {
        // xx/aa?b=123&q1=https -> 找出q1的位置
        // xx/aa?q1=https -> 找出q1的位置
        let schemeList = str.components(separatedBy: "=")
        let scheme = schemeList.last ?? ""
        let preList = UrlTool.subArray(schemeList, from: 0, size: schemeList.count - 1)
        // xx/aa?b=123&q1 -> 找出q1的位置
        // xx/aa?q1 -> 找出q1的位置
        let prSchemeStr = preList.joined(separator: "=")
        let charList = prSchemeStr.map{ String($0) }
        let chatCount = charList.count
        for i in (0..<chatCount) {
            let findI = chatCount - i - 1
            let charStr = charList[findI]
            if charStr == "?" || charStr == "&" {
                let preUrlStr = UrlTool.subArray(charList, from: 0, size: findI).joined()
                let keyStr = UrlTool.subArray(charList, from: findI+1, to: chatCount-1).joined()
                return (preUrlStr, keyStr, scheme)
            }
        }
        return (str, "", scheme)
    }
        // MARK: - 截取主URL上的参数
    private static func mainUrlParams(urlStr: String) -> [String: String] {
        var paramStr = urlStr
        if urlStr.contains("?") {
            let urlList = urlStr.components(separatedBy: "?")
            if urlList.count == 2 {
                // 标准的http://xxx?xx=xx&xx=xx
                paramStr = urlList.last ?? ""
            } else if urlList.count > 2 {
                let preStr = urlList.first ?? ""
                paramStr = UrlTool.subString(paramStr, from: preStr.count+1)
            }
        }
        // http:xx/aa?q1=https://xxx.yy/a?aa1=b&aa2=c&q2=okt://aa/b?d=dd&d2=ddd
        if paramStr.contains("?") {
            // 如果还包含?说明参数本身是链接
            let subUrlList = paramStr.components(separatedBy: "?")
            if subUrlList.count == 2 {
                let paramNormalList = paramStr.components(separatedBy: "=")
                let key = paramNormalList.first ?? ""
                let val = UrlTool.subString(paramStr, from: key.count+1)
                return [key: val]
            } else if subUrlList.count > 2 {
                // 有多个字url
            }
        }
        let pramsList = paramStr.components(separatedBy: "&")
        var pramsDict = [String: String]()
        for str in pramsList {
            if str.contains("=") {
                let keyValList = str.components(separatedBy: "=")
                pramsDict[keyValList.first ?? ""] = keyValList.last ?? ""
            }
        }
        return pramsDict
    }

    // MARK: - 给URL添加参数
    public static func appendUrlParam(urlStr: String, key: String, val: String) -> String {
        if urlStr.contains("?") == false {
            return "\(urlStr)?\(key)=\(val)"
        } else {
            return "\(urlStr)&\(key)=\(val)"
        }
    }
    public static func appendUrlParam(urlStr: String, paramsList: [(String,String)]) -> String {
        var urlPath = urlStr
        for (key, val) in paramsList {
            urlPath = UrlTool.appendUrlParam(urlStr: urlPath, key: key, val: val)
        }
        return urlPath
    }
    public static func appendUrlParams(urlStr: String, paramsDict: [String: String]) -> String {
        var urlPath = urlStr
        for (key, val) in paramsDict {
            urlPath = UrlTool.appendUrlParam(urlStr: urlPath, key: key, val: val)
        }
        return urlPath
    }
    
    // MARK: - subString方法
    private static func subString(_ str: String, from: Int) -> String {
        let fromOffset = from
        if from > str.count {
            return ""
        }
        let toOffset = str.count
        
        let startIndex = str.index(str.startIndex, offsetBy: fromOffset)
        let endIndex = str.index(str.startIndex, offsetBy: toOffset)
        return String(str[startIndex..<endIndex])
    }
    
    // MARK: - subArray方法
    private static func subArray(_ list: [String], from: Int, size: Int) -> Array<String> {
        return self.subArray(list, from: from, to: from+size-1)
    }
    
    private static func subArray(_ list: [String], from: Int, to: Int) -> Array<String> {
        // 包含from, 包含to
        let maxTo = list.count - 1
        if from > maxTo {
            return []
        }
        var toIndex = to
        if toIndex > maxTo {
            toIndex = maxTo
        }
        if toIndex < from {
            return []
        }
        return Array(list[from...toIndex])
    }
}

测试结果:

1
2
3
4
5
6
7
8
http://www.appleX.com/info?name=balana&age=18
["age": "18", "name": "balana"]
http://www.appleX.com/info?name=balana&age=18&callback=http://www.googleY.com&type=friend
["name": "balana", "callback": "http://www.googleY.com", "type": "friend", "age": "18"]
http://xx/aa?year=123&q1=https://xxx.yy/a?aa1=b&aa2=c&q2=fly://aa/b?d=dd&d2=ddd
["q2": "fly://aa/b?d=dd&d2=ddd", "q1": "https://xxx.yy/a?aa1=b&aa2=c", "year": "123"]
http://xx/aa?b=123&q1=https://xxx.yy/a?aa1=b&aa2=c&xx=wx://a&x=1&y=2&q2=sky://aa/b?d=dd&d2=ddd
["q2": "sky://aa/b?d=dd&d2=ddd", "y": "2", "b": "123", "xx": "wx://a", "x": "1", "q1": "https://xxx.yy/a?aa1=b&aa2=c"]
This post is licensed under CC BY 4.0 by the author.