NSurlconncetion received data length always 0 but file saving works - iphone

Hi i want to show the received bytes in the console.
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[receivedData length]];
NSLog(#"resourceData length: %d ", [resourceLength intValue]);
if (file) {
[file seekToEndOfFile];
}
[file writeData:data];
}
the file successfully downloads and safed it into docoument dir but the nslog show always
resourceData length: 0
receivedata is NSMutableData *receivedData; in the .h file
the strange thing is that the exceptedbytes work well. here the code for that:
- (void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse)response {
localFilename = [[[url2 absoluteString] lastPathComponent] copy];
NSLog(localFilename);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0] ;
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:localFilename];
[[NSFileManager defaultManager] createFileAtPath:appFile contents:nil attributes:nil];
expectedBytes = [response expectedContentLength];
NSLog(#"content-length: %lli Bytes", expectedBytes);
file = [[NSFileHandle fileHandleForUpdatingAtPath:appFile] retain];
if (file) {
[file seekToEndOfFile];
}
}
can somebody help me. i really dont know what i am doing wrong
kind regards
tammo

Have you allocated and initialised receivedData? One usually does
receivedData = [[NSMutableData data] retain];
right after creating an NSURLConnection instance, and then
[receivedData setLength:0];
upon receiving a response via -connection:didReceiveResponse:, and
[receivedData appendData:data];
upon receiving data via -connection:didReceiveData:. This is exemplified in the URL Loading System Programming Guide. If you haven’t instantiated receivedData, it is probably nil and [receivedData length] returns 0 in that case.

Related

Download video from Youtube

I'm going to download video from Youtube using PSYouTubeExtractor. Every thing is fine but the saved file does not contain any video. It has 283 byte size only. I don't know what thing I'm going to wrong. Please help I'm new to objective C. Any kind of response will be appreciated.
this is code that I've used for downloading
- (void)viewDidLoad {
[super viewDidLoad];
self.title = NSLocalizedString(#"YouTube", nil);
[self.navigationController.navigationBar setTitleTextAttributes:
[NSDictionary dictionaryWithObjectsAndKeys:
HELVETICA_NEUE_LIGHT_24,
NSFontAttributeName, nil]];
self.youtubeUrl_Label.text = NSLocalizedString(#"Enter YouTube URL:", nil);
self.youtubeUrl_Label.font = HELVETICA_NEUE_LIGHT_15;
self.go_button.titleLabel.text = NSLocalizedString(#"GO", nil);
self.go_button.titleLabel.font = HELVETICA_NEUE_LIGHT_15;
extractor = [[PSYouTubeExtractor alloc] init]; }
//////////////////////////////////////////////////////
-(IBAction)go_button:(id)sender {
NSString* textFieldString = [NSString stringWithFormat:#"%#",self.textField.text];
NSURL *youTubeURL = [NSURL URLWithString:textFieldString];
[extractor getVideoUrlForUrl:youTubeURL notificatoinName:#"URLDidFinishExtractingFromYouTubeURL"];
//NSURLConnection will download the video
con = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:youTubeURL] delegate:self];}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
videoData = [[NSMutableData alloc] init];}
////////////////////////////////////
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[videoData appendData:data]; }
////////////////
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString* mediaPath = [documentsDirectory stringByAppendingPathComponent:#"Media"];
if(![[NSFileManager defaultManager] fileExistsAtPath:mediaPath])
[[NSFileManager defaultManager] createDirectoryAtPath:mediaPath withIntermediateDirectories:NO attributes:nil error:nil];
NSString *filePath = [NSString stringWithFormat:#"%f.mp4",[[NSDate date] timeIntervalSince1970]];
NSString* finalPath = [mediaPath stringByAppendingPathComponent:filePath];
[videoData writeToFile:finalPath atomically:YES];
NSLog(#"LOCAL VIDEO LINK %#",filePath);}
XCDYouTubeVideoPlayerViewController Is the new version of PSYouTubeExtractor. PSYouTubeExtractor was discontinued 2 years ago. It is possible that the Youtube API changed, thus making the PSYouTubeExtractor useless.
If you really want to debug the problem, check out what the NSURLResponse is in:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
And print the data you get (in NSString UTF8)

downloading using NSURLConnection not downloading anything?

i am using NSURLConnection to download mp3 data from the server , my code is here
- (IBAction)downloadData:(id)sender
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *url = [[NSURL alloc] initWithString:#"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];
[request setURL:url];
[url release];
url = nil;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[responseData release];
[connection release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[responseData
length]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myFile"];
[responseData writeToFile:fileName atomically:YES];
responseData = nil;
self->imageConnection = nil;
}
am little bit confused about the path given to download. when i click download button i shows "Succeeded! Received 1329 bytes of data" but nothing is downloading. need some help. how will we specify the local path of iPhone to store downloaded data?
- (IBAction)downloadData:(id)sender
{
NSURL *url = [[NSURL alloc] initWithString:#"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];
NSMutableURLRequest *theRequest_to = [NSMutableURLRequest requestWithURL:url];
[url release];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest_to delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
{
NSString *filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"snehamethrayo.mp3"]; // here you can set your filename which you can get from url
[[NSFileManager defaultManager] createFileAtPath:filepath contents:nil attributes:nil];
file = [[NSFileHandle fileHandleForUpdatingAtPath:filepath] retain];// Here file is object of NSFileHandle and its declare in .h File
[file seekToEndOfFile];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[file seekToEndOfFile];
[file writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
[file closeFile];
}
No need for any code change I think.Just put an nslog and see...
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myFile"];
NSLog(#"%#",fileName);
That will list the file location like this
/Users/me/Library/Application Support/iPhone Simulator/5.0/Applications/(your app)/Documents/myFile. ie the downloaded file is in your document folder.
note: don't forget to put the file format ie
NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myFile.mp3"];

How to save downloaded data to device's filesystem

I'm downloading pdf documents from the server:
- (void)downloadSingleDocument:(NSURL *)url
{
[pdfData release];
pdfData = [[NSMutableData alloc] init];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req addValue:#"Basic **************=" forHTTPHeaderField:#"Authorization"];
downloadConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
NSLog(#"Connection did receive data");
[pdfData appendData:data];
}
On connectionDidFinishLoading I want to save downloaded pdf file to filesystem in Documents directory with the same filename as it was on the server.
What is the best way to do it?
Use this methods if you have large file:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response
{
filepath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:save_name];
[[NSFileManager defaultManager] createFileAtPath:filepath contents:nil attributes:nil];
file = [[NSFileHandle fileHandleForUpdatingAtPath:filepath] retain];// Here file is object of NSFileHandle and its declare in .h File
[file seekToEndOfFile];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[file seekToEndOfFile];
[file writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
[file closeFile];
// After you download your data. you can copy your data from here to filesystem. and remove from here
}
Use NSURLDownload.
Sorry, that is only available on the Mac, not for iOS.
Create a temporary file, and append the received data to it in connection:didReceiveData:. In connectionDidFinishLoading:, move the file to the correct place, and in connection:didFailWithError:, remove the temporary file.
This should do it
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSString *filename = [con.originalRequest.URL lastPathComponent];
NSString *path = [documentsDirectory stringByAppendingString:filename];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:path contents:pdfData attributes:nil];
}

NSMutableData Save to a File

I downloaed the file using code shown below. Then i am trying to save NSMutableData variable to file, however, the file is not created. What am i doing wrong? Do i need to convert NSMutableData into NSString?
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)_response {
response = [_response retain];
if([response expectedContentLength] < 1) {
data = [[NSMutableData alloc] init];
}
else {
data = [[NSMutableData dataWithCapacity:[response expectedContentLength]] retain];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)_data {
[data appendData:_data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"txt"];
NSLog(#"saved: %#", filePath);
[data writeToFile:filePath atomically:YES];
NSLog(#"downloaded file: %#", data); //all i see in log is some encoded data here
}
You can’t write inside your app’s bundle. You’ll need to save it somewhere else, like your app’s Documents directory:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"file.txt"];
[data writeToFile:filePath atomically:YES];

How to download a large file with the iPhone SDK and avoid memory usage issues?

I'm using the NSURLConnection class to download a large file in my iPhone application, but it crashes every so often because it's using too much memory. I'm doing the usual NSURLConnection usage, to append the received data to a NSMutableData object.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.fileData appendData:data];
}
Then after I finish downloading the whole file, I save it to a local temporary file, and read it as a mapped file like this:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// save the downloaded data into a temporary file
NSString *tempPath = NSTemporaryDirectory();
NSString *tempFile = [tempPath stringByAppendingPathComponent:#"temp.pdf"];
[self.fileData writeToFile:tempFile atomically:YES];
NSData *mappedData = [NSData dataWithContentsOfMappedFile:tempFile];
NSURL *baseURL = [NSURL URLWithString:#"http://mydomain.com"];
[webView loadData:mappedData MIMEType:#"application/pdf" textEncodingName:#"UTF-8" baseURL:baseURL];
}
What can I improve here to avoid these memory usage problems?
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response {
filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:save_name]; // filename is in .h file
[[NSFileManager defaultManager] createFileAtPath:filename contents:nil attributes:nil];
file =
[[NSFileHandle fileHandleForUpdatingAtPath:filename] retain];// file is in .h
//if (file) {
//
// [file seekToEndOfFile];
// }
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSD
ata *)data {
if (file) {
[file seekToEndOfFile];
} [file writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
[file closeFile];
}
If it's that large, why not write it to the file as it comes in, rather than keeping it in an NSData object?
i'm using
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:save_name];
NSFileHandle *file1 = [NSFileHandle fileHandleForUpdatingAtPath: filename];
[file1 writeData: data];
[file1 closeFile];
}