如何知道NSData的initWithContentsOfURL何时完成加载。

时间:2010-01-27 20:13:21

标签: iphone

我正在从xml和图像加载一些文本,该图像加载的时间比xml要长,但我想同时显示它们。

我正在使用

加载图片
NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgLink]];

如何设置一个回调函数,让我知道mydata有图像,所以我可以将图像和文本添加到视图中?

由于

1 个答案:

答案 0 :(得分: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