How to find out when NSData initWithContentsOfURL finished loading.

I am loading some text from xml and image, the image takes longer than xml, but I want to display them at the same time.

I upload an image using

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

How to set a callback function that lets me know what the mydataimage has, so that I can add the image and text to the view?

thank

+3
source share
1 answer

You will need to use NSURLConnection. It is quite simple, but more active 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;

, , .

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

. .

+6

Source: https://habr.com/ru/post/1730275/


All Articles