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

前端 未结 6 1380
不知归路
不知归路 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:21

    Use:

    guard let urlQuery =  URL(string: "https://en.wikipedia.org/wiki/Query_string?title=Main_page&action=raw")?.query else {
        return
    }
    
    let queryArray = urlQuery.characters.split { $0 == "&"}.map(String.init)
    var parametersDict: [String: String] = [:]
    for queryParameter in queryArray {
        // Split the queryParam into key / value
        let keyValueArray = queryParameter.characters.split{$0 == "="}.map(String.init)
        let key = keyValueArray.first
        let value = keyValueArray.last
        parametersDict.updateValue(value!, forKey: key!)
    }
    
    print(parametersDict)
    // Prints ["action": "raw", "title": "Main_page"]
    

提交回复
热议问题