iOS 关于URL编解码,替换对应key的value

func findValueFromUrl(urlStr: String, key: String) -> String {
        guard let urlComponents = NSURLComponents(string: urlStr) else {
            return ""
        }
        guard (urlComponents.queryItems?.count) != nil else {
            return ""
        }
        guard let queryItems = urlComponents.queryItems else {
            return ""
        }
        for item in queryItems {
            if item.name == key {
                return item.value ?? ""
            }
        }
        return ""
    }
    func appendNewValueToUrl(urlStr: String, param: String) -> String {
        if urlContainsParam(urlStr) {
            return urlStr + "&" + param
        } else {
            return urlStr + "?" + param
        }
    }
    
    @objc dynamic func urlContainsParam(_ url: String) -> Bool {
        guard let urlComponents = NSURLComponents(string: url) else {
            return false
        }
        return ((urlComponents.queryItems?.isEmpty) != nil)
    }
    func modifyParameter(urlStr: String, key: String, toValue: String) -> String {
        guard let urlComponents = NSURLComponents(string: urlStr) else {
            return ""
        }
        for i in 0..<(urlComponents.queryItems?.count ?? 0) {
            if urlComponents.queryItems?[i].name == key {
                urlComponents.queryItems?[i].value = toValue
            }
        }
        
        return urlComponents.url?.absoluteString ?? ""
    }
extension String {
    //将原始的url编码为合法的url
    func urlEncoded() -> String {
        var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
        allowedQueryParamAndKey.remove(charactersIn: "!*'\"();:@&=+$,/?%#[]% ")
        return self.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey) ?? ""
    }
        //将编码后的url转换回原始的url
        func urlDecoded() -> String {
            return self.removingPercentEncoding ?? ""
        }
    
}

你可能感兴趣的:(iOS 关于URL编解码,替换对应key的value)