0

下面的代码成功地从链接中获取图像并存储到我的缓存目录中。但我想从不同的 url 获取许多(比如 100 个)图像(但在同一个网站上,只有文件名不同)。这适用于拍摄这些图像,但我需要等待很长时间。无论如何可以轻松获取图像并使我的响应时间真正更快。

 NSString *UCIDLink = [NSString stringWithFormat:@"http://www.example.com/picture.png];
    NSURL * imageURL = [NSURL URLWithString:UCIDLink];
    NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"picture.png"]];       

    NSError *writeError = nil;
    [imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
    if (writeError) {
        NSLog(@"Success");
    }else{
        NSLog(@"Failed");
    }

生长激素

4

2 回答 2

1

您使用的代码需要时间来加载图像内容。所以,更喜欢异步加载图像。

使用以下代码:

dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
        dispatch_async(q, ^{
            /* Fetch the image from the server... */
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *img = [[UIImage alloc] initWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                /* This is the main thread again, where we set the tableView's image to
                 be what we just fetched. */
                cell.imgview.image = img;
            });
        });

或者您可以使用:

AsyncImageView *asyncImageView = [[AsyncImageView alloc]initWithFrame:CGRectMake(30,32,100, 100)];   
[asyncImageView loadImageFromURL:[NSURL URLWithString:your url]];
[YourImageView addSubview:asyncImageView];
[asyncImageView release];

从这里下载文件..... https://github.com/nicklockwood/AsyncImageView

于 2013-06-12T12:39:19.670 回答
0

使用多线程以使多个图像获取同时发生。这样,您可以大大减少等待时间。

于 2013-06-12T11:48:06.197 回答