0

I know its stupid to ask but i dont know where i am wrong. I am new to NSURLConnections. I have to download a file using NSURLConnection. here is my code:

NSURL *url = [NSURL URLWithString:@"http://www.comicbookresources.com/feed.php?feed=previews"];

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES ];
[self.data appendData:self.data];
NSString  *filePath = [NSString stringWithFormat:@"%u/%@", NSDocumentDirectory,@"usman.pdf"];
[self.data writeToFile:filePath atomically:YES];

it looks ridiculous but still i am asking

EDIT: I am sorry. I forgot to add word: asynchronous connection

iBug
  • 2,334
  • 3
  • 32
  • 65
  • 3
    `[self.data appendData:self.data];` what is this supposed to do? – DrummerB Dec 09 '13 at 12:59
  • Just use this post: http://stackoverflow.com/questions/5803673/how-to-make-nsurlconnection-file-download-work – mprivat Dec 09 '13 at 13:00
  • And did you read the documentation? There is a whole chapter on how to download files. https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLDownload.html#//apple_ref/doc/uid/20001839-BAJEAIEE – DrummerB Dec 09 '13 at 13:00
  • Use NSData *GETReply = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:&response error:nil]; [GETReply writeToFile:filePath atomically:YES]; – Pradhyuman sinh Dec 09 '13 at 13:01
  • And `[NSString stringWithFormat:@"%u/%@", NSDocumentDirectory,@"usman.pdf"]` returns something like "9/usman.pdf", but *not* a file path inside the document directory ... – Martin R Dec 09 '13 at 13:04

1 Answers1

6

try this ....

NSURL *url = [NSURL URLWithString:@"http://www.comicbookresources.com/feed.php?feed=previews"];

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES ];

then take one instance variable NSMutableData * mdata; // in .h file

after this implement NSURLConnectionDataDelegate methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
     mdata = [[NSMutableData alloc]init];
}

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


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     NSString  *filePath = [NSString stringWithFormat:@"%u/%@", NSDocumentDirectory,@"usman.pdf"];
     [mdata writeToFile:filePath atomically:YES];
}

happy coding :)

Shaik Riyaz
  • 11,204
  • 7
  • 53
  • 70