Swift - 解析包含URL的字符串

时间:2016-12-19 07:29:27

标签: ios swift string

如何解析此字符串:

  

http://www.ha *** *** ay.ir/pa NT / result_false.php?错误=取消%20By%20User

我尝试使用下面给出的代码将给定的字符串转换为字典。但我得到了这个错误:

  

无法读取数据,因为格式不正确。

这是我的代码:

 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
        }

1 个答案:

答案 0 :(得分:25)

可以使用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)