簡體   English   中英

花時間將圖像從URL加載到UIImageview

[英]Taking time to load the image from URL to UIImageview

我使用此代碼顯示從URL到UIImageview的圖像

UIImageView *myview=[[UIImageView alloc]init];

myview.frame = CGRectMake(50, 50, 320, 480);

NSURL *imgURL=[[NSURL alloc]initWithString:@"http://soccerlens.com/files/2011/03/chelsea-1112-home.png"];

NSData *imgdata=[[NSData alloc]initWithContentsOfURL:imgURL];

UIImage *image=[[UIImage alloc]initWithData:imgdata];

myview.image=image;

[self.view addSubview:myview];

但問題是它需要花費太長時間才能在imageview中顯示圖像。

請幫我...

有沒有辦法加快這個過程......

而不是dispatch_async,使用SDWebImage緩存圖像。

這是我見過的最好的......

dispatch_async的問題在於,如果您從圖像中失去焦點,它將再次加載。 但SDWebImage,緩存圖像,它不會再次重新加載。

Use Dispatch queue to load image from URL.


dispatch_async(dispatch_get_main_queue(), ^{

  });

Or add a placeholder image till your image gets load from URL.

在我自己的問題上給出的答案理解GCD塊[NSData dataWithContentsOfURL:URL]的行為確實有意義。所以如果你在GCD中使用[NSData dataWithContentsOfURL:URL] (這些天開發人員做的很多) )下載文件/圖像不是一個好主意。所以我傾向於以下方法(你可以使用NSOperationQueue )。

使用[NSURLConnection sendAsynchronousRequest:queue:completionHandler:加載圖像,然后使用NSCache防止一次又一次地下載相同的圖像。

正如許多開發人員所建議的那樣,請使用SDWebimage ,它確實包含了下載圖像文件的上述策略。您可以加載任意數量的圖像,並且根據代碼的作者不會多次下載相同的URL

編輯

關於[NSURLConnection sendAsynchronousRequest:queue:completionHandler:

NSURL *url = [NSURL URLWithString:@"your_URL"];
NSURLRequest *myUrlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:myUrlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{

    if ([data length] > 0 && error == nil)
        //doSomething With The data

    else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
        //time out error

    else if (error != nil)
        //download error
}];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM