2013-02-08 74 views
-1

如何將圖像下載到應用程序中?就像我想從我的網站獲取圖片並將其下載到該人的iPhone應用程序中以顯示在應用程序中?基本上這個圖像不會被url顯示。如何將圖像下載到應用程序中?

更具體:

如何將圖像下載到應用程序,而無需使用UIImage的。我想獲取圖像並將其下載爲文件名「anne.png」,然後使用UIImage將其作爲anne.png引用到整個應用程序中。請參閱 - 我想先下載它,這樣當有人第二次訪問應用程序時,他們會看到圖像,並在此期間看到默認圖像。謝謝。?

+5

[你嘗試過什麼?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2013-02-08 21:51:39

回答

0

對於單張圖像,您可以使用以下內容。請記住,這將阻止用戶界面直到圖像被完全下載。

[UIImage imageWithData:[NSData dataWithContentsOfURL:photoURL]]; 

爲了不阻塞UI下載圖片:

dispatch_queue_t downloadQueue = dispatch_queue_create(「image downloader」, NULL); 

dispatch_async(downloadQueue, ^{ 
    [NSData dataWithContentsOfURL:photoURL]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     UIImage *image = [UIImage imageWithData:imageData]; 
     // Code to show the image in the UI goes here 
    }); 
}); 

將圖像保存到你可以使用UIImageWriteToSavedPhotosAlbum手機相機膠捲。

將圖像保存在應用程序的目錄中。使用的NSData的writeToFile:atomically:

爲了從網站下載一些圖片,也許這可以幫助你:

What's the best way to download multiple images and display multiple UIImageView?

+0

如何將圖像下載到該應用程序不使用UIImage。我想獲取圖像並將其下載爲文件名「anne.png」,然後使用UIImage將其作爲anne.png引用到整個應用程序中。請參閱 - 我想先下載它,以便當有人第二次訪問應用程序時,他們會看到圖像。謝謝。? – Jasmine 2013-02-08 23:07:05

+0

@BamBam正如我上面所建議的那樣,在擁有'NSData'之後,你可以通過'writeToFile'來將其保存到永久存儲中。 – Rob 2013-02-08 23:21:33

0

http://mobiledevelopertips.com/cocoa/download-and-create-an-image-from-a-url.html

URL到遠程圖像

我們開始通過創建一個URL到遠程資源:

NSURL *url = [NSURL URLWithString: @"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"]; 

從NSData的

下一步是生成使用從URL下載的數據一個UIImage,它由包含遠程圖像內容的NSData對象的創建的UIImage:

UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 

將其組合在一起

以下是如何包裹它一起,加入遠程圖像作爲一個子視圖到現有的視圖通過創建一個UIImageView FR OM以上的UIImage:

NSURL *url = [NSURL URLWithString:@"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"]; 
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 
    [self.view addSubview:[[UIImageView alloc] initWithImage:image]]; 
+0

但它阻止?如果阻塞,我該怎麼辦?這會將圖像下載到個人的應用程序存儲? – Jasmine 2013-02-08 22:00:15

+0

你試過這個嗎?它被封鎖了嗎? – Garry 2013-02-08 22:01:22

+0

@BamBam您通常會在後臺隊列中執行第一步和第二步,並僅執行UI更新,即將主題「放在一起」。 – Rob 2013-02-08 22:46:17

相關問題