将图像保存到文档目录

时间:2011-01-09 13:44:36

标签: iphone image url

我正在获取大约1500个图像网址并希望将这些图像一次性存储在iphone的文档目录中? 请建议采取任何方法......

感谢

1 个答案:

答案 0 :(得分:3)

下载所有网址并写入一个文件的方法:

     - (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
    }

    }

您需要编写一个脚本,返回包含1400个链接的答案,以便您可以将其写入该文件。

将NSArray *提供的所有图像下载到文档目录的方法。

- (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];
}

注意:您需要将纯文件名读入NSArray。如果你有不同的起源改变

[NSString stringWithFormat:@"http://example.com/%@",filename]

[NSString stringWithFormat:@"%@",filename]

并将完整路径(http://example.com/file1.png,http://example.com/file2.png)读入NSArray。

完成。希望它会有所帮助。

很抱歉这么多编辑:S