How do I convert url.query to a dictionary in Swift?

前端 未结 6 1381
不知归路
不知归路 2021-02-09 02:06

I have a URL coming in to the AppDelegate method:

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) ->         


        
6条回答
  •  一整个雨季
    2021-02-09 02:17

    Simple Extension

    extension URL {
        var queryDictionary: [String: String]? {
            guard let query = self.query else { return nil}
    
            var queryStrings = [String: String]()
            for pair in query.components(separatedBy: "&") {
    
                let key = pair.components(separatedBy: "=")[0]
    
                let value = pair
                    .components(separatedBy:"=")[1]
                    .replacingOccurrences(of: "+", with: " ")
                    .removingPercentEncoding ?? ""
    
                queryStrings[key] = value
            }
            return queryStrings
        }
    }
    

    USAGE

    let urlString = "http://www.youtube.com/video/4bL4FI1Gz6s?hl=it_IT&iv_logging_level=3&ad_flags=0&endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vfl6o3XZn.swf&cid=241&cust_gender=1&avg_rating=4.82280613104"
    let url = URL(string: urlString)
    print(url!.queryDictionary ?? "NONE")
    

提交回复
热议问题