1

私のiPhoneアプリでは、Webからいくつかの画像をダウンロードしています。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 に答える