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

前端 未结 1 607
故里飘歌
故里飘歌 2020-12-19 22:37

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

相关标签:
1条回答
  • 2020-12-19 22:55

    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.

    0 讨论(0)
提交回复
热议问题