检查 url 是否有效,以便我可以将其传递给 NSURL?
我想检查 NSString
是否是有效的 URL,以便我可以将其解析为 NSURL
变量...有没有简单的方法可以做到这一点? :)
崩溃 由于某种原因,应用程序在检查时崩溃......
NSURL *shortURL = [[NSURL alloc] initWithString:data];
if(shortURL == nil)
{
NSLog(@"INVALID");
}
else {
NSLog(@"COOOL");
}
控制台给我这个错误......
* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* -[NSURL initWithString:relativeToURL:]:nil 字符串参数” 2010-03-01 19:24:14.797 Snippety[8289:5e3b] 堆栈:( 8307803, 2419510843, 8391739, 8391578, 2898550, 3152497, 12262, 12183, 27646, 2662269, 2661144, 2454790485, 2454790162 )
I want to check if an NSString
is a valid URL so I can parse it to an NSURL
variable... is there an easy way to do this? :)
CRASH
For some reason the app crashes when checking.....
NSURL *shortURL = [[NSURL alloc] initWithString:data];
if(shortURL == nil)
{
NSLog(@"INVALID");
}
else {
NSLog(@"COOOL");
}
The console gives me this error.....
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSURL initWithString:relativeToURL:]: nil string parameter'
2010-03-01 19:24:14.797 Snippety[8289:5e3b] Stack: (
8307803,
2419510843,
8391739,
8391578,
2898550,
3152497,
12262,
12183,
27646,
2662269,
2661144,
2454790485,
2454790162
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我使用以下方法来检查 NSString testString 是否是有效的 URL:
scheme 测试 URL 的前缀,例如 http://、https:// 或 ftp://
host 测试 URL 的域,例如 google.com 或 images.google.com
注意:这仍然会给您带来一些误报,例如在检查 http://google,com(注意逗号)将返回valid,但它绝对比仅仅检查 NSURL 是否不为 nil 更精确(
[NSURL urlWithString:@"banana"]
不为零)。I'm using the below method to check whether NSString testString is a valid URL:
scheme tests the prefix of the URL, e.g. http://, https:// or ftp://
host tests the domain of the URL, e.g. google.com or images.google.com
Note: This will still give you some false positives, e.g. when checking http://google,com (note the comma) will return valid but it's definitely more precise than just checking whether NSURL is not nil (
[NSURL urlWithString:@"banana"]
is not nil).编辑:以下答案不正确。 (苹果文档:https:// developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/index.html)
NSURL
的URLWithString 返回
nil
。因此,您只需检查返回值即可确定 URL 是否有效。例子:
Edit: the below answer is not true. (Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/index.html)
NSURL
'sURLWithString
returnsnil
if the URL passed is not valid. So, you can just check the return value to determine if the URL is valid.Example:
这基本上就是
+[NSURLConnection canHandleRequest:]
方法确实如此。此方法针对NSURLRequest
运行预检,以确保请求可解析。要快速检查特定 URL,您可以执行以下操作:This is basically what the
+[NSURLConnection canHandleRequest:]
method does. This method runs a preflight check against anNSURLRequest
to make sure the request is resolvable. To quickly check a particular URL, you can do this: