2013-06-12 60 views
0

以下代碼成功從鏈接中獲取圖片並存儲到我的緩存目錄中。但我想從不同的網址(但在同一網站上,只有文件名不同)很多(如100)圖像。這適用於拍攝這些圖像,但我需要等很長時間。無論如何,輕鬆獲取圖像並使我的響應時間更快。從網址保存圖片需要很長時間

NSString *UCIDLink = [NSString stringWithFormat:@"http://www.example.com/picture.png]; 
    NSURL * imageURL = [NSURL URLWithString:UCIDLink]; 
    NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"picture.png"]];  

    NSError *writeError = nil; 
    [imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError]; 
    if (writeError) { 
     NSLog(@"Success"); 
    }else{ 
     NSLog(@"Failed"); 
    } 

ghgh

+0

掙扎點是最有可能帶寬。所以任何改善你的帶寬都會加速這個過程。這與你的代碼無關。 –

+1

您同時運行多少個下載? – Wain

+0

@Bartdude感謝我獲得了高速連接,我確信這個概念在Android中實現,它的工作非常快。 – dinesh

回答

0

使用多線程,以便使一些圖像的獲取同時發生。這樣,你可以減少很多等待時間。

1

您使用的代碼需要時間來加載圖像內容。所以,更喜歡異步加載圖像。下面的代碼

使用:

dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
     dispatch_async(q, ^{ 
      /* Fetch the image from the server... */ 
      NSData *data = [NSData dataWithContentsOfURL:url]; 
      UIImage *img = [[UIImage alloc] initWithData:data]; 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       /* This is the main thread again, where we set the tableView's image to 
       be what we just fetched. */ 
       cell.imgview.image = img; 
      }); 
     }); 

,或者您可以使用:

AsyncImageView *asyncImageView = [[AsyncImageView alloc]initWithFrame:CGRectMake(30,32,100, 100)]; 
[asyncImageView loadImageFromURL:[NSURL URLWithString:your url]]; 
[YourImageView addSubview:asyncImageView]; 
[asyncImageView release]; 

從這裏下載文件..... https://github.com/nicklockwood/AsyncImageView