[英]Swift - Parse a string which contains a URL
How can parse this string :如何解析这个字符串:
http://www.ha ***ay.ir/pa***nt/result_false.php?error=Canceled%20By%20User
http://www.ha ***ay.ir/pa***nt/result_false.php?error=Canceled%20By%20User
I tried using the code given below for converting the given string to a dictionary.我尝试使用下面给出的代码将给定的字符串转换为字典。 But I got this error :
但我收到了这个错误:
The data couldn't be read because it isn't in the correct format.
无法读取数据,因为它的格式不正确。
This is my code :这是我的代码:
func webViewDidFinishLoad(_ webView: UIWebView) {
print("finish loading")
let yourTargetUrl = webView.request?.url?.absoluteString
print(yourTargetUrl!)
let parse = convertToDictionary(text: yourTargetUrl!)
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
The query
part of an URL can be parsed with URLComponents
URL 的
query
部分可以用URLComponents
解析
let yourTargetUrl = URL(string:"http://www.foo.ir/baz/result_false.php?error=Canceled%20By%20User")!
var dict = [String:String]()
let components = URLComponents(url: yourTargetUrl, resolvingAgainstBaseURL: false)!
if let queryItems = components.queryItems {
for item in queryItems {
dict[item.name] = item.value!
}
}
print(dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.