iOS从URL中解析query的key&value对

Swift 3现在提供了内置方法,可以做个简单的封装:

extension String {
    /// 假设string是url,抽取key&value对
    func tt_urlQueryDict() -> [String: String] {
        var dict = [String:String]()
        guard let queryItems = URLComponents(string: self)?.queryItems else {
            return dict
        }

        for qi in queryItems {
            let key = qi.name
            let value = qi.value
            dict[key] = value
        }

        return dict
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *