Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Parse a string which contains a URL

Tags:

string

ios

swift

How can parse this string :

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
}
like image 942
ava Avatar asked Dec 19 '16 07:12

ava


1 Answers

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)
like image 123
vadian Avatar answered Sep 28 '22 17:09

vadian