2010-01-27 89 views
3

我正在從xml和圖像中加載一些文本,該圖像比xml加載時間要長,但我想同時顯示它們。如何知道NSData的initWithContentsOfURL何時完成加載。

我加載使用

NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgLink]]; 

如何設置一個回調函數,讓我知道mydata有圖像的圖像,這樣我就可以同時添加圖像和文本的看法?

謝謝

回答

6

您將不得不使用NSURLConnection。這相當簡單,但比NSData方法涉及更多。

首先,創建一個NSURLConnection的:

NSMutableData *receivedData; 

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:imgLink] 
              cachePolicy:NSURLRequestUseProtocolCachePolicy 
             timeoutInterval:60.0]; 

NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

if (theConnection) { 
    receivedData=[[NSMutableData data] retain]; 
} else { 
    // inform the user that the download could not be made 
} 

現在,添加<NSURLConnectionDelegate>到類的頭和實現以下方法:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; 
- (void)connectionDidFinishLoading:(NSURLConnection *)connection; 

第一個應該追加數據,如下所示,最後一個應該創建並顯示圖像。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; 
{ 
    // append the new data to the receivedData 
    // receivedData is declared as a method instance elsewhere 
    [receivedData appendData:data]; 
} 

查看this document瞭解更多詳情。

+0

我希望這聽起來不笨,但是:我已經在同一個類中使用NSURLConnection來處理另一件事了。所以...我怎麼知道委託方法正在被調用時,做一個或其他的事情,並採取相應的行動? – pabloruiz55 2010-01-27 21:42:24

+0

您的委託方法的連接參數將發生更改。 – 2013-08-31 08:06:36

相關問題