Reputation: 4958
i am new to Objective-C and going through the book, The Big Nerd Ranch Guide to Objective-C programming..
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSURL *url = [NSURL URLWithString:@"http://www.google.com/imagess/logos/ps_logo2.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error =nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:NULL
error:&error];
if(!data){
NSLog(@"fetch failed %@", [error localizedDescription]);
return 1;
}
NSLog(@"the files is %lu bytes", [data length]);
BOOL written = [data writeToFile:@"/tmp/google.png"
options:NSDataWritingAtomic
error:&error];
if(!written){
NSLog(@"write failed: %@",[error localizedDescription]);
return 1;
}
NSLog(@"Success!");
NSData *readData = [NSData dataWithContentsOfFile:@"/tmp/google.png"];
NSLog(@"the file read from disk has %lu bytes", [readData length]);
}
return 0;
}
the problem is this, if i change the *url to http://aFakeDomain.com/imimimi/myImage.png then my data object will be nill because there is no HOST and everything works fine.. but if i use google as the domain and point to a bad file location then the data object stil has header info and is NOT nil thus i never get the error i should.
whats the best way to make sure that the *url successfully found a file.
thanks
Upvotes: 1
Views: 453
Reputation: 247
There are also some mistakes of the file name; instead of @"/tmp/google.png", you should use the code list blow:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"google.png"];
Upvotes: 0
Reputation: 5909
You will need to pass a response to the NSURLConnection
call and then check its status code:
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&httpResponse
error:&error];
int code = [httpResponse statusCode];
you will get a 404
status code in your case.
Upvotes: 3
Reputation:
NSUrlResponce *responce = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&responce
error:&error];
if (error) {
// handle the error
}
if (![[responce MIMEType] isEqualToString:@"image/png"]) {
// failed to get png file
}
Upvotes: 2