How to make NSURLConnection file download work?

后端 未结 3 2041
醉梦人生
醉梦人生 2021-01-25 04:12

I have a ViewController declared as:

@interface DownloadViewController : UIViewController 
           
<         


        
3条回答
  •  萌比男神i
    2021-01-25 05:02

    Using a UIViewController instead of an NSObject should not be your problem here ! I'm using a NSURLConnection in an UIViewController with no issue ! Here is a part of my code (not sure it will compile as it is) :

    //
    //  MyViewController.h
    //
    
    #import 
    
    @interface MyViewController : UIViewController {
        @protected
        NSMutableURLRequest* req;
        NSMutableData* _responseData;
        NSURLConnection* nzbConnection;
    }
    
    - (void)loadFileAtURL:(NSURL *)url;
    
    @end
    

    -

    //
    //  MyViewController.m
    //
    
    #import "MyViewController.h"
    
    @implementation MyViewController
    
    - (void)loadView {  
    // create your view here
    }
    
    - (void) dealloc {
        [_responseData release];
    
        [super dealloc];
    }
    
    #pragma mark -
    
    - (void)loadFileAtURL:(NSURL *)url {
        // allocate data buffer
        _responseData = [[NSMutableData alloc] init];
    
        // create URLRequest
        req = [[NSMutableURLRequest alloc] init];
        [req setURL:_urlToHandle];
    
        nzbConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
        [req release];
        req = nil;
    }
    
    
    #pragma mark -
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
        // Append data in the reception buffer
        if (connection == nzbConnection)
            [_responseData appendData:data];
    }
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        if (connection == nzbConnection) {
            [nzbConnection release];
            nzbConnection = nil;
    
            // Print received data
            NSLog(@"%@",_responseData);
    
            [_responseData release];
        }
    }
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
        // Something went wrong ...
        if (connection == nzbConnection) {
            [nzbConnection release];
            [_responseData release];
        }
    }
    
    @end
    

    If you plan to download large files, consider storing the received packets in a file instead of storing it in memory !

提交回复
热议问题