Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

iphone - how to know when NSData's initWithContentsOfURL has finished loading.

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.

I am loading the image using

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

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?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will have to use NSURLConnection. This is fairly straightforward, but more involved than the NSData method.

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
}

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];
}

See this document for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...