我在网上找到了把网页的图片保存到应用作为背景的方法,就是速度太慢了。
10kb的图片如果一张还可以,如果有15-20张,就像卡住了似的。有没有什么方法可以让从网上直接下载图片速度快一些?图片是批量下载的。而且还能保持图片质量。
#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) {
}
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];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end