NSURLConnection Download multiple images

后端 未结 2 2055
清歌不尽
清歌不尽 2021-01-14 19:45

I am trying to download multiple images from a URL stored in an XML feed. Getting the image urls from the XML is working correctly. However, the NSURLConnection is creating

2条回答
  •  我在风中等你
    2021-01-14 20:03

    You can use a CustomURLConnection with Tag to name de images before they download.

    With this code you can make a customURLConnection, name it when you make the request, and ask for the name of the image in the connectionDidFinishLoading:

    CustomURLConnection.h

    #import 
    
    @interface CustomURLConnection : NSURLConnection 
    {
    NSString *tag;
    }
    
    @property (nonatomic, retain) NSString *tag;
    
    - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)aTag;
    
    @end
    

    CustomURLConnection.m

    #import "CustomURLConnection.h"
    
    @implementation CustomURLConnection
    
    @synthesize tag;
    
    - (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)aTag 
    {
    self = [super initWithRequest:request delegate:delegate startImmediately:startImmediately];
    
        if (self) {
            self.tag = aTag;
        }
        return self;
    }
    
    - (void)dealloc 
    {
        [tag release];
        [super dealloc];
    }
    
    @end
    

    Then make the connection, a custom url connection in your parsingComplete with:

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:yourURL];
    [request setTimeoutInterval:3000.0];
    
    CustomURLConnection *connection = [[CustomURLConnection alloc]     initWithRequest:request delegate:self startImmediately:YES tag:imageTag];
    

    Now you can take the imageName with the CustomURLConnection tag, and save it in the connectionDidFinishLoading:

    CustomURLConnection *urlConec = (CustomURLConnection*)connection;
    
    NSMutableData *dataFromConnection = [self dataForConnection:urlConec];
    

    and this is the code for the function dataForConnection:

    - (NSMutableData*)dataForConnection:(CustomURLConnection*)connection 
    {
        NSMutableData *data = [receivedData objectForKey:connection.tag];
        return data;
    }
    

    Hope that helps.

提交回复
热议问题