Replace %20 with space character while saving file iOS - objective-c

I am now recording audio file and saving to document directory. The given name contain space character. When I save to document directory, space characters are changed to %20. I would like to know how to save properly so that that audio file name contain space character.
NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:recordingAudioName ];
NSURL *recordedTmpFile = [NSURL fileURLWithPath:myDBnew];
Edited - This is to do audio recording and save to local directory.
recorder = [[ AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:recordSetting error:&error];

You're using NSURL and spaces are invalid characters in a URL. That's why it's converted to a %20.

please use
-(BOOL)writeToFile:options:error:
instead of
-(BOOL)writeToURL:options:error:.
writeToFile takes a NSString as argument (not a NSURL). The spaces are preserved this way.
NSString *myDBnew = [documentsDirectory stringByAppendingPathComponent:recordingAudioName];
NSerror *error;
if (![data writeToFile:myDBnew options:0 error:&error]) {
// Error handling
}

Related

Can't read text file from desktop using objective-c

Can anyone help me to find what's wrong with my code while reading file from desktop
NSString *filename=#"~/Users/user12345/Desktop/Sample/Data.txt";
NSString *fileString=[NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:nil];
NSArray *namesArray=[fileString componentsSeparatedByString:#"\n"];
for(NSString *names in namesArray)
{
NSLog(#"names:%#",names);
}
If you want to use the tilde – which represents /User/<currentUser>/ – you have to ...expandingTildeInPath and remove /Users/user12345
NSString *filename = [#"~/Desktop/Sample/Data.txt" stringByExpandingTildeInPath];
that makes the path independent of the current user name, otherwise remove the tilde:
NSString *filename = #"/Users/user12345/Desktop/Sample/Data.txt";
Caveat: If your app is sandboxed the path does not point to the visible desktop.
NSString *filename=#"~/Users/user12345/Desktop/Sample/Data.txt";
The ~ used in a path is a convention which means your home directory, but it doesn't work in all contexts (e.g. when used in -stringWithContentsOfFile:`) and you've supplied an absolute path anyway. Remove it from the front of your path
NSString *filename=#"/Users/user12345/Desktop/Sample/Data.txt";
and it should work as long as the file does actually exist at that path.

escaping spaces in local url

i have the following code to try and load a local html page in a cocoa app...
NSString *basePath = #"file//Users/david/Documents/My Project/index.html";
NSString *escapedPath = [basePath stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSURL*url=[NSURL URLWithString:escapedPath];
NSURLRequest*request=[NSURLRequest requestWithURL:url];
NSLog(#"current file is %#", url);
Unfortunately, the url is always null, and if i look at the value of escapedPath i see '%20' escaping the space. however, this doesn't work in local. is there a stringBy function that escapes correctly for a local path?
Thanks!
For local paths you need to use fileURLWithPath:
See the docs here:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html

Weird problem with NSString initWithContentsOfFile

I have a .csv file in my bundle which I need to parse into an NSArray. The problem is when I init an NSString with contents of file (the file is located in my bundle), it returns nil. However, if I change the contents of the file, to anything else (random), it works. Is it possible there's some sort of string/character in the file that might be messing with the initialization?
It's just a simple csv file with 2 columns, a number, a comma, some text and "\n".
Thanks.
CSV => NSArray?
https://github.com/davedelong/CHCSVParser
*disclaimer: I wrote it.
Works for me:
NSStringEncoding usedEncoding = 0;
NSError *csvError = nil;
NSString *raw = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://pastebin.com/raw.php?i=RXPPwpvy"] usedEncoding:&usedEncoding error:&csvError];
NSLog(#"raw: %#", raw);
NSLog(#"%#", [NSArray arrayWithContentsOfCSVString:raw encoding:usedEncoding error:&csvError]);

Read and write an integer to/from a .txt file

How can I read and write an integer to and from a text file, and is it possible to read or write to multiple lines, i.e., deal with multiple integers?
Thanks.
This is certainly possible; it simply depends on the exact format of the text file.
Reading the contents of a text file is easy:
// If you want to handle an error, don't pass NULL to the following code, but rather an NSError pointer.
NSString *contents = [NSString stringWithContentsOfFile:#"/path/to/file" encoding:NSUTF8StringEncoding error:NULL];
That creates an autoreleased string containing the entire file. If all the file contains is an integer, you can just write this:
NSInteger integer = [contents integerValue];
If the file is split up into multiple lines (with each line containing one integer), you'll have to split it up:
NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *line in lines) {
NSInteger currentInteger = [line integerValue];
// Do something with the integer.
}
Overall, it's very simple.
Writing back to a file is just as easy. Once you've manipulated what you wanted back into a string, you can just use this:
NSString *newContents = ...; // New string.
[newContents writeToFile:#"/path/to/file" atomically:YES encoding:NSUTF8StringEncoding error:NULL];
You can use that to write to a string. Of course, you can play with the settings. Setting atomically to YES causes it to write to a test file first, verify it, and then copy it over to replace the old file (this ensures that if some failure happens, you won't end up with a corrupt file). If you want, you can use a different encoding (though NSUTF8StringEncoding is highly recommended), and if you want to catch errors (which you should, essentially), you can pass in a reference to an NSError to the method. It would look something like this:
NSError *error = nil;
[newContents writeToFile:#"someFile.txt" atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (error) {
// Some error has occurred. Handle it.
}
For further reading, consult the NSString Class Reference.
If you have to write to multiple lines, use \r\n when building the newContents string to specify where line breaks are to be placed.
NSMutableString *newContents = [[NSMutableString alloc] init];
for (/* loop conditions here */)
{
NSString *lineString = //...do stuff to put important info for this line...
[newContents appendString:lineString];
[newContents appendString:#"\r\n"];
}

objective c - does not read utf-8 encoded file

I'm trying to display some japanese text on the ios simulator and an ipod touch. The text is read from an XML file. The header is:
<?xml version="1.0" encoding="utf-8"?>
When the text is in english, it displays fine. However, when the text is Japanese, it comes out as an unintelligible mishmash of single-byte characters.
I have tried saving the file specifically as unicode using TextEdit. I'm using NSXMLParser to parse the data. Any ideas would be much appreciated.
Here is the parsing code
// Override point for customization after application launch.
NSString *xmlFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"questionsutf8.xml"];
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath];
NSData *data = [NSData dataWithBytes:[xmlFileContents UTF8String] length:[xmlFileContents lengthOfBytesUsingEncoding: NSUTF8StringEncoding]];
XMLReader *xmlReader = [[XMLReader alloc] init];
[xmlReader parseXMLData: data];
stringWithContentsOfFile: is a deprecated method. It does not do encoding detection unless the file contains the appropriate byte order mark, otherwise it interprets the file as the default C string encoding (the encoding returned by the +defaultCStringEncoding method). Instead, you should use the non-deprecated [and encoding-detecting] method stringWithContentsOfFile:usedEncoding:error:.
You can use it like this:
NSStringEncoding enc;
NSError *error;
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath
usedEncoding:&enc
error:&error];
if (xmlFileContents == nil)
{
NSLog (#"%#", error);
return;
}
First, you should verify with TextWrangler (free from the Mac app store or barebones.com) that your XML file truly is UTF-8 encoded.
Second, try creating xmlFileContents with +stringWithContentsOfFile:encoding:error:, explicitly specifying UTF-8 encoding. Or, even better, bypass the intermediate string entirely, and create data with +dataWithContentsOfFile:.