Swift-解析包含URL的字符串 [英] Swift - Parse a string which contains a URL
本文介绍了Swift-解析包含URL的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何解析此字符串:
http://www.ha *** ay.ir/pa***nt/result_false.php?error =已取消%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.
这是我的代码:
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
}
推荐答案
URL的 query
部分可以使用 URLComponents
The query
part of an URL can be parsed with 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)
这篇关于Swift-解析包含URL的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文