NSData file type validation - iphone

I'm consuming a web service that should return a wav file. I capture the result in an NSData object and save it to the local documents director.
How do I verify that the data is indeed a wav before saving it? If there were an error on the server, it may return a long string of HTML garbage.
Thanks!
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:RequestURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
NSHTTPURLResponse* response = nil;
NSData *soundData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
//save voicemail file locally
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *destPath = [documentsDirectory stringByAppendingPathComponent:#"returned.wav"];
[fileManager createFileAtPath:destPath contents:soundData attributes:nil];

There is 2 way to do this (hope that one of them will be acceptable for you):
1) check NSHTTPURLResponse's statusCode (type NSInteger) (should be equal to 200, if everything is ok),
2) check NSHTTPURLResponse's MIME type (type NSString *) (if I'm not wrong, should be #"audio/vnd.wave")

Related

How to get path of file to save data after getting data from server?

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:strFileUrl]]; //strFileURL is url of my video/image
NSURLConnection *conection = [[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO] autorelease];
[conec start];
[request release];
with use of above code i am creating URL connection to download data from server.
strFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:strFileName];
with use above code i can get path of file to save data, but in the above code i don't know how to get strFileName (at last in the above code) or please any one help me how to save data into my document directory after getting data from server. Advance thanking to all.
//Capturing server response
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[(NSURLResponse *)response suggestedFilename]];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:fullPath contents:result attributes:nil];

storing pdf on local doesnt work in iphone

I'm new with iPhone development. I want to download a pdf using url and want to store it in a local folder.
Here is my code:
NSData *d = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://demo.com/ebookapplication/book_pdf/20111108094614hii.pdf"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myfile.pdf"];
[d writeToFile:path atomically:YES];
if (![[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:#"myfile" ofType:#"pdf"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager copyItemAtPath:myPathInfo toPath:path error:NULL];
}
NSURL *pdfurl = [NSURL fileURLWithPath:path];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:pdfurl];
[detail.bookweb loadRequest:requestObj];//to display data in web view
This code is working for display pdf in web view using url, but it doesn't work for storing pdf in our local system. Actually I want to store these downloaded pdf in one folder and and display it in library format. Please help.
-writeToFile:Atomically has already placed your file in the folder you've specified in the -copyItemAtPath:toPath: method, and is thus redundant. The document was already in the documents directory folder, you then copied it over to the same directory! I think that's your problem.
EDIT:
This Line HERE:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"myfile.pdf"];
specifies your path.
You can NSLog it with this line: NSLog(#"Document Path = %#", path);
As for your library comment, it shouldn't be that hard. My app, which basically does this already, wires
AQGridView: https://github.com/AlanQuatermain/AQGridView
And Apple's Docwatcher class from DITableView: http://developer.apple.com/library/ios/samplecode/DocInteraction/Listings/Classes_DITableViewController_h.html
Together to create an app that trolls the documents directory and adds files to an NSArray which are then displayed by the grid. A simpler approach would just be to use the DITableViewController though, considering it solves your problems, it's just the grid was for a little more pizzaz.

Create and save NSString data in to a file

i have 3NSString objects that i want to save to a new file when the app is running.
this will help me for remote debug!
if any one can help me creating the file and save the data to it will be very use full
thanx
You can save the files to the Documents directory, here is how to get the path to that directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
And a sample write statement:
NSError *error;
BOOL status = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
In the NSString documentation there is method called writeToFile:atomically:encoding:error:.
NSError *error;
[#"Write me to file" writeToFile:#"<filepath>" atomically:YES encoding: NSUTF8StringEncoding error:&error];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents directory
NSError *error; BOOL succeed = [myString writeToFile:[documentsDirectory stringByAppendingPathComponent:#"myfile.txt"]
atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!succeed){
// Handle error here }
source.
Here is how to save NSString into Documents folder. Saving other types of data can be also realized that way.
- (void)saveString:(NSString *)stringToSave toDocumentsWithFilename:(NSString *)fileName {
NSString *documentsFolder = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *path = [documentsFolder stringByAppendingPathComponent:fileName];
[[NSFileManager defaultManager] createFileAtPath:path contents:[stringToSave dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
}
Usage:
NSString *stringWeWantToSave = #"This is an elephant";
NSString *fileName = [NSString stringWithString:#"savedString.txt"];
[self saveString:stringWeWantToSave toDocumentsWithFilename:fileName];

i can unzip the folder but how to access that folder form iphone

this code allows you to unzip file and create a folder in documents lets say List and this List folder is having all the unzip data now how to access that List content??
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *saveLocation =
[documentsDirectory stringByAppendingString:#"myfile.zip"];
NSFileManager* fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:saveLocation]) {
[fileManager removeItemAtPath:saveLocation error:nil];
NSLog(#" file path %#",fileManager);
}
NSURLRequest *theRequest =
[NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://localhost/list.zip"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSData *received =
[NSURLConnection sendSynchronousRequest:theRequest
returningResponse:nil error:nil];
if ([received writeToFile:saveLocation atomically:TRUE]) {
NSString *cmd =
[NSString stringWithFormat:#"unzip \"%#\" -d\"%#\"",
saveLocation, documentsDirectory];
// Here comes the magic...
system([cmd UTF8String]);
}
NSLog(#"loca is %#", saveLocation);
NSLog(#"%#", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil]); // i can see list folder but how to get the content outside??
to unzip file on iphone read this - http://www.touch-code-magazine.com/update-dynamically-your-iphone-app-with-new-content/
You can access it with NSFileManager's
- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error.

iphone writeTofile error

im getting a "CFDictionaryAddValue(): immutable collection 0xd5aea0 given to mutating function"
error when i try to write a string to a file using the follwowing code
NSString *xmlString = [NSString stringWithString:xmlData];
NSError *error = nil;
if ([xmlString writeToFile:filePath atomically:NO encoding:NSASCIIStringEncoding error:&error])
xmlData was a mutable string but xmlString is not.
any ideas?
It works for me in cocoa.
NSString * xmlData = #"This is some random string";
NSString * xmlString = [NSString stringWithString:xmlData];
NSError * error = nil;
if (![xmlString writeToFile:#"data.txt"
atomically:NO
encoding:NSASCIIStringEncoding
error:&error])
{
NSLog(#"writeToFile failed: %#", error);
}
I would check:
How do you get xmlData? Is it a NSString?
Do you specify file path within your app bundle? You will not be able to write outside your application directory apart from Documents (?) I think.
This is how you would specify file in Documents directory:
// Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
// <Application Home>/Documents/foo.plist
NSString *fooPath = [documentsPath stringByAppendingPathComponent:#“foo.plist”];