'Swift Get Fragment in url

I need to take specific fragment in url

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print(webView.url?.fragment)            
    }

In webView Delegate i check the url when page finish loading , if in the url i find the fragment , in my case #access_token , i want save it and close the Web page .

For the moment i can only do this print(webView.url?.fragment) but print all the fragment , i want ONLY #access_token .

exaple url :

https://example.com/oauth-callback#access_token=<TOKEN_NUMBER>&scope=....



Solution 1:[1]

i found a way to get the fragment , i use Regex of type ECMAScript.

            let fragment: String? = webView.url?.fragment
        
        if ((fragment?.contains("access_token")) != nil) {
            let pattern = #"access_token=(.*)&scope"#
            let regex = try! NSRegularExpression(pattern: pattern)
            let testString = fragment
            
            let stringRange = NSRange(location: 0, length: testString!.utf16.count)
            let matches = regex.matches(in: testString!, range: stringRange)
            var result: [[String]] = []
            for match in matches {
                var groups: [String] = []
                for rangeIndex in 1 ..< match.numberOfRanges {
                    let nsRange = match.range(at: rangeIndex)
                    guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
                    let string = (testString! as NSString).substring(with: nsRange)
                    groups.append(string)
                }
                if !groups.isEmpty {
                    result.append(groups)
                }
            }
            let token = result.first
            print(token as Any)
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alexmasu