0

我正在开发一个 iOS 应用程序,该应用程序由一个静态 sqlite 数据库、一系列表视图和基于选项卡的详细视图组成,其中在详细视图中加载的第一个视图是一个可滑动的 imageView,它加载了一系列图像。

我已经使用此代码在本地查找图像,但我想让它从 URL 加载图像,或者如果没有可用的 Internet 连接,则显示默认图像。

这些图像在数据库中被命名为(例如)image.jpg,我希望它们都从同一个 URL 目录(例如)http://www.someurl.com/images/加载

谢谢

- (UIImage *) imageAtIndex:(NSUInteger)index {

Image  *currentImage = (Image *) [self.images objectAtIndex:index];

NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@",[[currentImage filename] stringByDeletingPathExtension]] ofType:@"jpg"];

return [UIImage imageWithContentsOfFile:path];
}
4

2 回答 2

0

The process for this is really very simple:

  1. Try to download your image data using NSURLConnection
  2. If successful, create a UIImage from the data
  3. If either of the above fails, switch over to your placeholder/built-in image
  4. Display the resulting image

I advise you have some sort of placeholder while the image is downloading, since that can take quite a while.

Don't bother with reachability; it's not 100% reliable, whereas actually trying the download is.

Avoid doing this on a background thread or queue. NSURLConnection is asynchronous out of the box to make this easier for you. There are a ton of third-party frameworks that try to simplify working with connections if you wish, though.

于 2013-04-09T13:06:26.530 回答
-1
NSString *urlStr = [@"http://www.someurl.com/images/" stringByAppendingString:[currentImage filename]];
NSURL *url = [NSURL URLWithString:urlStr];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [[UIImage alloc] initWithData:data];

或类似的东西...

如果图像很大或者网络连接很慢,NSData 初始化可能需要一些时间。考虑在后台线程中获取图像数据,或使用一些现有的框架,如SDWebImage

于 2013-04-02T16:40:18.630 回答