我在網上找到了把網頁的圖片保存到應用作為背景的方法,就是速度太慢了。
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
你先檢查一下電腦上的浏覽器下載圖片的時間多少。有可能是圖片服務器端的問題呢
然後試一些提高的代碼,比如AsyncImageView,
刪除存儲然後再次測試,看看是不是快了一點。
你干嘛要在主線程下載?你應該在background線程下載,然後在主線程更新。你現在的方法會阻塞主線程。