If url exists Objective-c
Hey, I have a program that needs to tell if an online image exists, but the only way that I've gotten this to work is by loading the image in a NSData pointer and checking if the pointer exists.
- (BOOL)exists {
NSString *filePath = @"http://couleeapps.hostei.com/BottomBox.png";
NSURL *url = [NSURL URLWithString:filePath];
NSData *imageData = [NSData dataWithContentsOfURL:url];
if (imageData) {
return YES;
}
return NO;
}
This has worked for me, but my problem is that I have a very slow connection, and it takes forever to download the image. So my question is: is there a way to put checking if a开发者_Go百科 image (say "http://couleeapps.hostei.com/BottomBox.png") is available without having to download it in a Boolean reporter method?
Help is much appreciated
HiGuy
Create an NSURLConnection
to fetch the url. Set the HTTPMethod
of the NSURLRequest
to "HEAD"
instead of "GET"
. In the delegate method connection:didReceiveResponse:
check the statusCode
of the NSHTTPURLResponse
for 200 or other success response.
-(void) queryResponseForURL:(NSURL *)inURL {
NSMutableURLRequest request = [NSMutableURLRequest requestWithURL:inURL];
[request setHTTPMethod:@"HEAD"];
NSURLConnection connection = [NSURLConnection connectionWithRequest:request delegate:self];
// connection starts automatically
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ( [(NSHTTPURLResponse *)response statusCode] == 200 ) {
// url exists
}
}
There could be other status codes that you would treat as success, like 301.
Part of the HTTP protocol is setting the request method. GET and POST are the two most common, but there are several others including HEAD. HEAD says send the same response you would send for GET, but do not send the body. In your case the body is the image data. So if HEAD succeeds, you can assume that GET would also succeed in the same way, at least in the case of looking up a static resource.
connectionWithRequest is depreciated. So you have to use dataTaskWithRequest:
-(void) queryResponseForURL:(NSURL *)inURL {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:inurl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"HEAD"];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSUInteger respCode=[(NSHTTPURLResponse *)response statusCode];
if ( !error&&respCode == 200 ) {
// url exists
} else {
// url does not exist
}
}];
[postDataTask resume];
}
精彩评论