views:

148

answers:

1

Hi. I am trying to make a app to take photos off of a website, and save them to the NSDocumentDirectory for later usage. So far I have failed in my attempts, and am wondering how to do it.

Not much more explanation is needed, but here are a few of my (failed) tries:
One:

NSString *path = @"http://miniwidgit.webs.com/TabRight2.png";
NSFileManager *fmgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [[NSString alloc] initWithFormat:@"%@/File.jpg", documentsDirectory];
NSLog(fileName);
NSError *err;
if ([fmgr copyItemAtPath:path toPath:fileName error:&err]) {
} else {
NSLog([NSString stringWithFormat:@"%@%@.", @"There was an error. The error was: ", err]);
}

Two:

NSURL *path = [NSURL URLWithString:@"http://miniwidgit.webs.com/TabRight2.png"];
NSFileManager *fmgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [[NSString alloc] initWithFormat:@"%@/File.jpg", documentsDirectory];
NSLog(fileName);
NSError *err;
NSString *image = [[NSString alloc] initWithContentsOfURL:path];
[image writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionExternalRepresentation error:&err];
NSLog([NSString stringWithFormat:@"%@%@.", @"There was an error. The error was: ", err]);

On One, I got the error: Error Domain=NSPOSIXErrorDomain Code=2 UserInfo=0x3b171b0 "Operation could not be completed. No such file or directory," but this does not make sense, because the image (on my site) exists. On Two, I got the error: Error Domain=NSCocoaErrorDomain Code=517 UserInfo=0x3b33090 "Operation could not be completed. (Cocoa error 517.)"

So if you have a solution, please answer this!

HiGuy

+3  A: 

That isn't a file path — it's a URL for an HTTP resource. You need to use one of the URL-loading APIs (e.g. NSURLDownload) to download the image.

With the code you have now in No. 1, it's looking for a file called "TabRight2.png" which is in a directory called "miniwidget.webs.com" which is in a directory called "http:" which is in the current directory — and of course not finding one.

With the second one, you're trying to load an image into an NSString. It's hard to say what the exact error is in that case, but that's inadvisable and might be the culprit. NSStrings are for text, and images can contain sequences that aren't valid as text in any encoding. You should use NSData to store binary data, not NSString.

Chuck