我想知道网址即时提供是否有效,以及网上是否存在..
使用objective-C有没有办法做到这一点?
答案 0 :(得分:2)
通过执行以下操作,您可以查看网址是否有效:
NSString *urlString = ... // some URL to check
NSURL *url = [NSURL URLWithString:urlString];
if (url) {
// valid URL (meaning it is the proper format)
}
要查看Internet中是否存在URL,您需要执行HEAD请求并检查结果。这比加载URL的所有数据更有效。
NSMutableURLRequest request = [NSMutableURLRequest requestWithURL:inURL];
[request setHTTPMethod:@"HEAD"];
NSURLConnection connection = [NSURLConnection connectionWithRequest:request delegate:self];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([(NSHTTPURLResponse *)response statusCode] == 200) {
// url exists
}
}