2013-07-15 182 views
1

在我的iPhone应用程序中,我从网上下载一些图像。不管它是否阻塞UI线程,实际上它需要阻塞UI线程直到完全下载。完成后,我会通知用户界面将其唤醒并显示出来。NSData writeToFile在模拟器上工作,但不在设备上

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

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在图像存储之前醒来。几乎所有的图像都是空的。

我在做什么错?

+0

有什么目标路径? – Brad

+0

检查writeToFile返回的错误。 –

+0

@Brad - 它是应用程序支持下的一个目录。 –

回答

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); 
     } 

    } 

}]; 
1
  1. 检查您的设备是否可以下载这些图片,访问Mobile Safari中的图片网址进行测试。 dataWithContentsOfURL:将返回零或它不是一个正确的图像数据,如404未找到
  2. 日志错误[data writeToFile:filePath]查看保存的详细信息。
+0

+1有关dataWithContentsOfURL的指导原则。 –

相关问题