2014-09-18 115 views
2

我有一些代碼從網頁獲取圖像並將其顯示在ImageView中。但由於某種原因,圖像加載非常緩慢,我不太明白!通過我的日誌記錄,我可以看到圖像的所有數據(base64字符串)都很快到達,但圖像出現在ImageView中需要大約12到15秒。UIImageView加載圖像很慢

我覺得這很奇怪,因爲我使用NSStream以不同的方法獲取圖像的數據,並在所有數據到達時加載圖像。但是使用這個URLSession方法需要更長的時間才能加載圖像。這真的沒有道理!此方法不應該影響ImageView加載該數據的方式。

有沒有人有任何想法,爲什麼這可能會發生?

繼承人的代碼:

- (void)postMethod:(NSDictionary *)numDict 
{ 
NSURL *url = [NSURL URLWithString:@"http://theWebAddress.com/aPage.php"]; // add url to page 
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 
request.HTTPMethod = @"POST"; 


NSError *error = nil; 
NSData *data = [NSJSONSerialization dataWithJSONObject:numDict options:kNilOptions error:&error]; 

NSLog(@"%@", numDict); 

if (!error) 
{ 
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

     NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 


     for (id key in diction) 
     { 
      if ([key isEqualToString:@"text"]) 
      { 
       NSLog(@"data is text"); 

       self.messageLabel.text = diction[@"text"]; 

       break; 
      } 
      else if ([key isEqualToString:@"image"]) 
      { 
       NSLog(@"data is an image"); 

       // gets the base64 string pretty instantly but takes 12 - 15 seconds to pop up in the imageView 

       NSData *ImgData = [[NSData alloc] init]; 
       ImgData = [[NSData alloc] initWithBase64EncodedString:diction[@"image"] options:1]; 

       self.ImageView.image = [UIImage imageWithData:ImgData]; 

       break; 
      } 
     } 

    }]; 

    [uploadTask resume]; 
} 
} 

非常感謝!

+0

爲什麼使用上傳任務? – 2014-09-18 21:51:05

+0

因爲我發佈了一些數據到網頁上,那麼頁面會根據這些數據輸出文本或圖像。 – ThriceGood 2014-09-18 22:56:57

回答

8

你完成處理程序可能會在後臺線程進行操作。 UI更新應始終在主線程上運行。把一個斷點在

self.ImageView.image = [UIImage imageWithData:ImgData]; 

看看它是否在主線程。如果沒有,請在設置ImageView.image之前將其發送到主線程:

dispatch_async(dispatch_get_main_queue(), ^{ 
    self.ImageView.image = [UIImage imageWithData:ImgData]; 
}); 
+1

就像一個魅力!儘管你的代碼在第一個{'dispatch_async(dispatch_get_main_queue(),^ {code})之前丟失了^; ' 非常感謝! – ThriceGood 2014-09-19 17:39:29

+0

是的,謝謝你的提示。在SO中寫了一個快速的答案,而不是xcode,所以我沒有抓住它。 – mitrenegade 2014-09-19 17:54:34

0

您首先要下載圖片,然後顯示圖片。您可以使用延遲加載下載圖片。

爲此,您可以使用EgoImageView而不是uiimageview。

self.ImageView.imageURL = [NSURL URLWithString:

這裏self.ImageView是egoimageview類型。

你可以從github上得到這個類。

https://github.com/enormego/EGOImageLoading

2

你可以嘗試使用SDWebImage https://github.com/rs/SDWebImage,所有你需要的是設置在圖像中的ImageView這樣的:

[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] 
       placeholderImage:[UIImage imageNamed:@"placeholder.png"]];