I'm using a function that fixes URLs that can't be loaded directly into a WKWebView.
I rely on the NSDataDetector for checking whether the URL is valid or not.
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
NSUInteger numberOfMatches = [detector numberOfMatchesInString:URLString options:0 range:NSMakeRange(0, URLString.length)];
if (!error && numberOfMatches > 0) {
// Valid URL
}
else {
// Invalid URL
// Custom code runs here to fix it...
}
Here's the example where it doesn't work:
"/d.scdn.com/images/photo.jpg" ---> "http://stockimages.com/d.scdn.com/images/photo.jpg"
This is how the conversion should be done but instead it recognizes
"/d.scdn.com/images/photo.jpg"
As a valid URL and the fix code doesn't execute.
As you can see the problem with the example above is that a domain name is nested inside the string which I want to fix fooling the NSDataDetector for an actual URL.
Is there a way to take advantage of the numberOfMatches to solve this problem? Is there something like a minimum number of matches for a URL to be valid in relationship with the original string?