我在一些关于将图像从网站保存到 iphone 应用程序的论坛帖子上发现,我正在使用它,因为除了一件事,速度之外一切都很好。
图像大约10KB,当只有一张图像时下载速度还可以,但是当有15-20张图像时下载速度很慢。
我知道必须有办法以另一种方式更快地下载图像,因为我的 iPhone 上有一些新闻应用程序,并且这个应用程序下载了 15-20 篇带有我的图像的文章(我说喜欢我的图像,因为质量相同或更好)并且大约快 5 秒(或更多)。
所以我的问题是;是否有另一种更快的方式将图像从网站下载到 iPhone 应用程序?
这是我的代码:
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#import "downloadImage.h"
@interface downloadImage ()
@end
@implementation downloadImage
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *imgUrl = @"http://somesite.com/someimage.jpg";
dispatch_async(kBgQueue, ^{
[self performSelectorOnMainThread:@selector(downloadImageFromWeb:) withObject:imgUrl waitUntilDone:YES];
});
}
-(void)downloadImageFromWeb:(NSString *)imgUrl{
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]]];
NSArray *parts = [imgUrl componentsSeparatedByString:@"/"];
NSString *imgFilename = [parts lastObject];
[self saveImage:image:imgFilename];
}
- (void)saveImage:(UIImage*)image:(NSString*)imageName {
NSData *imageData = UIImageJPEGRepresentation(image, 100);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:
imageName];
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
//NSLog(@"image saved");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end