What's the best way to validate a user-entered URL in a Cocoa app?

I am trying to create a homegrown web browser to get more knowledge in Cocoa. I need a good way to check if a user is entered with a valid URL. I tried some regexes, but NSString has some interesting quirks and dislikes some of the inverse quotes that most regexes I've seen.

+4
source share
2 answers

You can start with the + (id)URLWithString:(NSString *)URLString NSURL , which returns nil if the string is incorrect.

If you need additional validation, you can use the baseURL , host , parameterString , path , etc. methods to provide you with specific URL components, which can then be evaluated in whatever way you see fit.

+5
source

I found that you can enter some URLs that look fine but are rejected by the NSURL creation methods. Therefore, we have a way to avoid the string first, to make sure that it is in good format. Here is his meat:

  NSString * escapedURLString =
     NSMakeCollectable (CFURLCreateStringByAddingPercentEscapes (NULL,
       (CFStringRef) URLString,
       (CFStringRef) @ "% + #", // Characters to leave unescaped
       NULL
       kCFStringEncodingUTF8));
+4
source

Source: https://habr.com/ru/post/1277662/


All Articles