1

在我的 iphone 应用程序中,我正在从网上下载一些图像。是否阻塞UI线程无关紧要,实际上它需要阻塞UI线程直到完全下载。完成后,我通知 UI 唤醒并显示它们。

我的(简化的)代码是这样的:

for (int i=0; i<10; i++)
{
    //call saveImageFromURL (params)
}
//Call to Notify UI to wake up and show the images

+(void) saveImageFromURL:(NSString *)fileURL :(NSString *)destPath :(NSString *)fileName
{
    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];

    NSFileManager * fileManager = [NSFileManager defaultManager];

    BOOL bExists, isDir;
    bExists = [fileManager fileExistsAtPath:destPath isDirectory:&isDir];

    if (!bExists)
    {
        NSError *error = nil;
        [fileManager createDirectoryAtPath:destPath withIntermediateDirectories:YES attributes:nil error:&error];
        if (error)
        {
            NSLog(@"%@",[error description]);
            return;
        }
    }

    NSString *filePath = [destPath stringByAppendingPathComponent:fileName];
    [data writeToFile:filePath options:NSAtomicWrite error:nil];
}

当我完成for循环后,我很确定所有图像都存储在本地。它在模拟器中运行良好。

但是,它在我的设备上效果不佳。UI 在图像存储之前唤醒。几乎所有的图像看起来都是空的。

我究竟做错了什么?

4

2 回答 2

1
  1. 检查您的设备是否可以下载这些图像,请访问 Mobile Safari 中的图像 URL 进行测试。dataWithContentsOfURL:将返回 nil 或者它不是正确的图像数据,例如 404 not found
  2. 记录错误[data writeToFile:filePath]以查看保存的详细信息。
于 2013-07-15T20:58:49.663 回答
0

经过一番研究,我曾经AFHttpClient enqueueBatchOfHTTPRequestOperations完成多个文件下载。

这是怎么回事:

//Consider I get destFilesArray filled with Dicts already with URLs and local paths

NSMutableArray * opArray = [NSMutableArray array];
AFHTTPClient *httpClient = nil;

for (id item in destFilesArray)
{
    NSDictionary * fileDetailDict = (NSDictionary *)item;
    NSString * url = [fileDetailDict objectForKey:@"fileURL"];
    if (!httpClient)
            httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:url]];

    NSString * filePath = [photoDetailDict objectForKey:@"filePath"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];          

    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
    [opArray addObject:operation];
}    

[httpClient enqueueBatchOfHTTPRequestOperations:opArray progressBlock:nil completionBlock:^(NSArray *operations)
{
    //gets called JUST ONCE when all operations complete with success or failure
    for (AFJSONRequestOperation *operation in operations)
    {

        if (operation.response.statusCode != 200)
        {                
            NSLog(@"operation: %@", operation.request.URL);
        }

    }

}];
于 2013-07-17T16:11:33.077 回答