i am fetching around 1500 image url and want to store these images in the document directory of iphone at one go?? please suggest any approach to do开发者_JS百科 it...
thanks
Method to download all URLs and write into one file:
- (BOOL) downloadFilefromCDN :(NSString*)filename {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://example.com/getlinks.php"]]];
[request setHTTPMethod:@"GET"];
NSError *err = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
if (err != nil) { return FALSE; } // Download error
NSArray *searchPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[searchPath objectAtIndex:0] stringByAppendingString:[NSString stringWithFormat:@"/%@",filename]];
if ([data writeToFile:path atomically:YES] != FALSE) {
return TRUE;
} else {
return FALSE; // Error
}
}
You need to write a script that returns an answer including the 1400 links so you can write it into that file.
Method to download all images given by a NSArray* to document directory.
- (id) downloadFilefromCDN :(NSString*)filename {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://example.com/%@",filename]]];
[request setHTTPMethod:@"GET"];
NSError *err = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
if (err != nil) { return FALSE; }
return data;
}
- (NSArray*) downloadFilesfromCDN :(NSArray*)filenames {
NSMutableArray *mfiles = [[NSMutableArray alloc] init];
BOOL error = FALSE;
for (NSString* filename in filenames) {
NSArray *searchPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[searchPath objectAtIndex:0] stringByAppendingString:[NSString stringWithFormat:@"/%@",filename]];
id file = [self downloadFilefromCDN:filename];
if ([file isKindOfClass:[NSData class]]) {
if ([(NSData*)file writeToFile:path atomically:YES] != FALSE) {
[mfiles addObject:path];
} else {
error = TRUE; // Writing of file failed
}
} else {
error = TRUE; // Download failed
}
}
if (error) {
// Handle error
}
[filenames release];
return [NSArray arrayWithArray:mfiles];
}
Note: You need to read the pure filenames into a NSArray. If you have different origins change
[NSString stringWithFormat:@"http://example.com/%@",filename]
to
[NSString stringWithFormat:@"%@",filename]
and read the full paths (http://example.com/file1.png,http://example.com/file2.png) into a NSArray.
Done. Hope it will help.
Sorry for so much editing :S
精彩评论