如何知道NSData的initWithContentsOfURL何时完成加载。 [英] how to know when NSData's initWithContentsOfURL has finished loading.
问题描述
我正在从xml和图像加载一些文本,该图像加载的时间比xml要长,但我想同时显示它们。
I am loading some text from xml and an image, that image takes longer to load than the xml, but I want to show them at the same time.
我正在使用
NSData *mydata = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgLink]];
如何设置回调函数让我知道 mydata
有图像,所以我可以将图像和文本添加到视图中吗?
How can I set a callback function that lets me know that mydata
has the image, so I can add both the image and the text to the view?
谢谢
推荐答案
您必须使用NSURLConnection。这相当简单,但比NSData方法更复杂。
You will have to use NSURLConnection. This is fairly straightforward, but more involved than the NSData method.
首先,创建一个NSURLConnection:
First, create an 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>到你的类的标题并实现以下方法:
Now, add <NSURLConnectionDelegate> to the header of your class and implement the following methods:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
第一个应该附加数据,如下所示,最后一个应创建并显示图片。
The first one should append the data, as shown below, and the final one should create and display the image.
- (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];
}
参见本文档了解更多详情。
这篇关于如何知道NSData的initWithContentsOfURL何时完成加载。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!