3

I am a noob in NSURLConnection. I have searched Google and found this site but I dont understand about it.

My friends please explain the code that I have downloaded from url in Document folder.

This is my code :

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *url =[NSURL URLWithString:@"http://cdn.arstechnica.net/wp-content/uploads/2012/09/iphone5-intro.jpg"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *con  = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [con start];}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //I dont know what thing put here
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
    //I dont know what thing put here
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //I dont know what thing put here
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"The Connection has been LOST" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
Liam
  • 27,717
  • 28
  • 128
  • 190
david
  • 147
  • 3
  • 12
  • Refer apple docs : http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html – Anil May 09 '13 at 05:09

3 Answers3

5

Using NSURLConnection ,Try this

// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg"]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData to hold the received data.
    // receivedData is an instance variable declared elsewhere.
    receivedData = [[NSMutableData data] retain];
} else {
    // Inform the user that the connection failed.
}

For more info on NSURLConnection Refer this :URL Loading System Programming Guide

EDIT

Here recievedData is the instance variable of type NSMutableData

-(void)downloadWithNsurlconnection
{

    NSURL *url = [NSURL URLWithString:currentURL];
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:url         cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
    receivedData = [[NSMutableData alloc] initWithLength:0];
    NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self     startImmediately:YES];


}


- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [receivedData setLength:0];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];


}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:@".jpg"]];
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [receivedData writeToFile:pdfPath atomically:YES];
}
Lithu T.V
  • 19,955
  • 12
  • 56
  • 101
3

It would be good to do it asynchronously with NSURLConnection with blocks.

- (NSString *)documentsDirectoryPath{
    NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                               NSUserDomainMask,
                                                               YES);
    return directories[0];
}

- (void)downloadImage{

    NSString *urlPath = @"http://cdn.arstechnica.net/wp-content/uploads/2012/09/iphone5-intro.jpg";
    NSURL *url = [NSURL URLWithString:urlPath];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:urlRequest
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * response, NSData *responseData, NSError *error) {

                               if (responseData) {
                                   NSString *imageName = [urlPath lastPathComponent];
                                   NSString *imagePath = [[self documentsDirectoryPath]stringByAppendingPathComponent:imageName];

                                   [responseData writeToFile:imagePath atomically:YES];
                               }

    }];
}
Anupdas
  • 10,211
  • 2
  • 35
  • 60
2

Without using NSURLConnection you can easily download files, then no need to overhead delegate calls. Simply try this.

NSString *url = @"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg";
NSArray *path               = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentdirectory = [path objectAtIndex:0];
NSString *dataPath          = [documentdirectory stringByAppendingPathComponent:@"Pictures"];
NSString *localFileURL      = [NSString stringWithFormat:@"%@/%@",dataPath,[url lastPathComponent]];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];

NSData   *data         = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
if([data writeToFile:localFileURL atomically:YES])
{
    NSLog(@"Downloaded File");
}
βhargavḯ
  • 9,786
  • 1
  • 37
  • 59
  • I know my friend but I want download file with NSURLConection... can you help me? – david May 09 '13 at 05:11
  • @david Please look at this http://stackoverflow.com/questions/3464252/how-to-download-a-file-by-using-nsurlconnection – βhargavḯ May 09 '13 at 05:16
  • "However in general, NSData's dataWithContentsOfURL should only be use to access local file resources." http://stackoverflow.com/a/21961737/505093 – kwahn Sep 22 '15 at 16:52