Objective c 从字符串创建有效的URL

Objective c 从字符串创建有效的URL,objective-c,Objective C,有没有API或好的函数可以像这样格式化字符串 “www.example.com”或仅“example.com”转换为有效的URL字符串,如 "http://www.example.com“ 这就是当前解决方案的外观,但在我看来,这并不是很好和可靠。使用NSDataDetector可以相当轻松地做到这一点: NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:NU

有没有API或好的函数可以像这样格式化字符串 “www.example.com”或仅“example.com”转换为有效的URL字符串,如 "http://www.example.com“


这就是当前解决方案的外观,但在我看来,这并不是很好和可靠。

使用
NSDataDetector可以相当轻松地做到这一点:

NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:NULL];
NSString *URLString = @"www.example.com";
NSTextCheckingResult *result = [detector firstMatchInString:URLString options:0 range:NSMakeRange(0, URLString.length)];
if (result) {
    NSURL *URL = [result URL];
    NSLog(@"%@", URL); // http://www.example.com
}
您不应该假设
www
是任何给定域的有效子域


如果您需要将结果作为字符串,可以使用
NSURL
absoluteString
方法,但是对于URL,通常最好使用
NSURL
而不是
NSString

使用
NSDataDetector
可以相当轻松地做到这一点:

NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:NULL];
NSString *URLString = @"www.example.com";
NSTextCheckingResult *result = [detector firstMatchInString:URLString options:0 range:NSMakeRange(0, URLString.length)];
if (result) {
    NSURL *URL = [result URL];
    NSLog(@"%@", URL); // http://www.example.com
}
您不应该假设
www
是任何给定域的有效子域


如果您需要将结果作为字符串,可以使用
NSURL
absoluteString
方法,但是对于URL,通常最好使用
NSURL
而不是
NSString

您当前拥有的内容非常糟糕。因为它没有考虑很多可能性。您可能希望使用正则表达式检查是否有有效的URL,而不是componentsSeparatedByString。目前,你的代码将忽略一个字符串,这将是糟糕的。你目前拥有的是非常糟糕的。因为它没有考虑很多可能性。您可能希望使用正则表达式检查是否有有效的URL,而不是componentsSeparatedByString。目前,你的代码将忽略一个字符串,这将是很糟糕的。非常感谢,这是我一直在寻找的解决方案。汉克斯,这是我一直在寻找的解决方案