How to read a text file ,turn it into a string, then using arguments on it - ios

Say If I had a string = "There were %# apples,I ate %#. Now I have %# apples" in text file "Apples.txt". This is how I will extract the text from it.
NSString *path = [[NSBundle mainBundle] pathForResource:#"Apples" ofType:#"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
Now how do I pass the arguments to it so it looks like this:
"There were %# apples,I ate %#. Now I have %# apples", x, y, x-y
I am sure there is a way around this using NString with arguments? using
NSString with local argument functions? otherwise I will have to type all of my text in the file.m
This very crucial for my app.

You are probably looking for [NSString stringWithFormat:...].
Your complete code goes like this :
NSString *path = [[NSBundle mainBundle] pathForResource:#"Apples" ofType:#"txt"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSNumber *total = #100;
NSNumber *ate = #34;
NSString *fullString = [NSString stringWithFormat:content,total,ate, #([total integerValue] - [ate integerValue])];
NSLog(#"%#", fullString);
Output:
"There were 100 apples,I ate 34. Now I have 66 apples".

Use + stringWithFormat:
Here's the Apple reference

Related

NSTask not working for file path with special characters

I am using NStask to get the folder size.Its working fine for normal file paths like home/ABC/Users/testUser/Documents. But it is not showing any output for file path like home/ABC/Users/testUser/Ω≈ç∂√√√∂ƒ∂.However I am getting proper output for the same file path on terminal. Any suggestion?
NSString* userName = #"test123_test123";
NSString* password = #"test";
NSString* serverIP = #"200.144.172.210";
NSString* sizeFolderPath = [[NSBundle mainBundle] pathForResource:#"demoUtilities" ofType:nil];
NSString* xml= #"--test";
NSString* passwordArg = [NSString stringWithFormat:#"--pwd-=%#",password];
NSString *filePath = #"UsersMac/Users/test/Ω≈ç∂√√√∂ƒ∂";
NSString* address = [NSString stringWithFormat:#"%##%#::home/%#", userName, serverIP,filePath];
NSArray* arguments = [NSMutableArray arrayWithObjects:xml,passwordArg,address,nil];
TestCommandExcecuter *cmExec = [[TestCommandExcecuter alloc]init];
[cmExec setCommandString:sizeFolderPath];
[cmExec setCommandArguments:arguments];
I am using this code:
Depricated from 2.0
NSDictionary *fileDictionary = [[NSFileManager defaultManager]
fileAttributesAtPath:filePath traverseLink:YES];
long long size = [fileDictionary fileSize];
NSLog(#"size :: %lld",size);
Latest :
NSDictionary *fileDictionary = [[NSFileManager defaultManager]
attributesOfItemAtPath:filePath error:nil];
long long size = [fileDictionary fileSize];
NSLog(#"size :: %lld",size);
Here is the reference link :
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/occ/instm/NSFileManager/attributesOfItemAtPath%3aerror%3a

iOS use ID3Lib to edit ID3 tags from mp3 files in the NSDocsDir

I am using ID3Lib example project to edit Title, Album and Artist ID3 tags on mp3 files and all is good until I come to adding an image (cover Art) if any one has any ideas how to finish off the below code that would be great:
- (void)demo {
nImage = [UIImage imageNamed:#"amazing-grace.jpg"];//unused
NSString *imagePath = [[NSBundle mainBundle] pathForResource:#"amazing-grace" ofType:#"jpg"];
NSString *path = [[NSBundle mainBundle] pathForResource:#"amazing-grace-10s" ofType:#"mp3"];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [[docPaths objectAtIndex:0] stringByAppendingPathComponent:#"amazing-grace-10s.mp3"];
[[NSFileManager defaultManager] copyItemAtPath:path toPath:docPath error:nil];
// Read title tag
ID3_Tag tag;
tag.Link([path UTF8String]);
ID3_Frame *titleFrame = tag.Find(ID3FID_TITLE);
unicode_t const *value = titleFrame->GetField(ID3FN_TEXT)->GetRawUnicodeText();
NSString *title = [NSString stringWithCString:(char const *) value encoding:NSUnicodeStringEncoding];
NSLog(#"The title before is %#", title);
// Write title tag
tag.Link([docPath UTF8String]);
tag.Strip(ID3FID_TITLE);
tag.Strip(ID3FID_ALBUM);
tag.Strip(ID3FID_LEADARTIST);
tag.Clear();
ID3_Frame frame;
frame.SetID(ID3FID_TITLE);
frame.GetField(ID3FN_TEXTENC)->Set(ID3TE_UNICODE);
NSString *newTitle = nTitle;
frame.GetField(ID3FN_TEXT)->Set((unicode_t *) [newTitle cStringUsingEncoding:NSUTF16StringEncoding]);
ID3_Frame frame2;
frame2.SetID(ID3FID_ALBUM);
frame2.GetField(ID3FN_TEXTENC)->Set(ID3TE_UNICODE);
NSString *newAlbum = nAlbmum;
frame2.GetField(ID3FN_TEXT)->Set((unicode_t *) [newAlbum cStringUsingEncoding:NSUTF16StringEncoding]);
ID3_Frame frame3;
frame3.SetID(ID3FID_LEADARTIST);
frame3.GetField(ID3FN_TEXTENC)->Set(ID3TE_UNICODE);
NSString *newArtist = nArtist;
frame3.GetField(ID3FN_TEXT)->Set((unicode_t *) [newArtist cStringUsingEncoding:NSUTF16StringEncoding]);
//this is the image code
ID3_Frame frame4;
frame4.SetID(ID3FID_PICTURE);
frame4.GetField(ID3FN_TEXTENC)->Set(ID3TE_UNICODE);// dont think this should be TEXTENC
NSString *newImage = imagePath;
frame4.GetField(ID3FN_DATA)->FromFile((const char *)[newImage cStringUsingEncoding:NSUTF16StringEncoding]);//this line is also probably wrong
tag.AddFrame(frame);
tag.AddFrame(frame2);
tag.AddFrame(frame3);
tag.AddFrame(frame4);
tag.SetPadding(false);
tag.SetUnsync(false);
tag.Update(ID3TT_ID3V2);
NSLog(#"The title after is %# The album after is %# The artist after is %# The artist after is %#", newTitle,newAlbum,newArtist,newImage);
}
Use file path with UTF-8 encoding and will work fine:
frame.GetField(ID3FN_DATA)->FromFile((const char *)[newImage cStringUsingEncoding:NSUTF8StringEncoding]);
I get this code, From this source: https://android.googlesource.com/platform/external/id3lib/+/8a58cac9f8db5ed55b02b3ac24156d628af923d1/examples/test_pic.cpp
frame.SetID(ID3FID_PICTURE);
frame.GetField(ID3FN_MIMETYPE)->Set("image/jpeg");
frame.GetField(ID3FN_PICTURETYPE)->Set(11);
frame.GetField(ID3FN_DESCRIPTION)->Set("B/W picture of Saint-Saëns");
//frame.GetField(ID3FN_DATA)->FromFile("composer.jpg");
frame.GetField(ID3FN_DATA)->FromFile((const char *)[newImage cStringUsingEncoding:NSUTF8StringEncoding]);
tag.AddFrame(frame);
And! this work nice. :D

How to read last n lines in a Text file in Objective C

I have a Text file and it has lot of lines How can i get last 'n' number of lines from the text file? and Can we give Numbers in the text file for each file How can we get it.
You could use NSFileHandle, seekToEndOfFile and then work backwards from the offsetInFile using seekToFileOffset: and readDataOfLength: scanning the data read each time for carriage returns and counting them until you get to the required number. As you go you can build up the text after each scan.
One way is putting \n to separate your different lines in the text file. Then
NSString* path = [[NSBundle mainBundle] pathForResource:#"filename"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSArray* lines = [content componentsSeparatedByString: #"\n"];
Then you can take the last few elements in the array.
Hope this helps..
Try to use this one:
NSString* textFile = [[NSBundle mainBundle]
pathForResource:#"fileName" ofType:#"txt"];
NSString* fileContents = [NSString stringWithContentsOfFile: textFile
encoding: NSUTF8StringEncoding error: nil];
Separate by new line
NSArray* allLinedStrings =
[fileContents componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]];
Here you can get your last 100 objects
NSString* oneLineStr;
for (int i = allLinedStrings.count - 100; i < allLinedStrings.count; i++)
{
oneLineStr = [allLinedStrings objectAtIndex: i];
NSLog#("New Line %#", oneLineStr);
}

editing occurrences is not working

i am trying to get the path to a certain file
and then open it in a webview. so i need to replace each space by '%20'
NSString *test=#"filename";
NSString *finalPath12 = [test stringByAppendingString:#".pdf"];
NSString *path1 = [[NSBundle mainBundle] bundlePath];
NSString *finalPath1 = [path1 stringByAppendingPathComponent:finalPath12];
NSString *file =#"file://";
NSString *htmlfilename1 = [file stringByAppendingString:finalPath1];
NSString *pathtofile = [htmlfilename1 stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
any string is working except #"%20".
this works perfectly for exemple:
NSString *pathtofile = [htmlfilename1 stringByReplacingOccurrencesOfString:#" " withString:#"string"];
but i need the #"%20". What am i missing ? Thanks
There is already [NSString stringByAddingPercentEscapesUsingEncoding:] (reference) for that very purpose.
However in your case, as you want a URL, you can replace all the lines in your question with:
NSURL *url = [[NSBundle mainBundle] urlForResource:#"filename" withExtension:#"pdf"];
You need to use #"%%20".
As first % is treated as escape/wild character.
Or use
stringByAddingPercentEscapesUsingEncoding:

Parsing and processing Text Strings in iOS

Wanted to find the best programming approach in iOS to manipulate and process text strings. Thanks!
Would like to take a file with strings to manipulate the characters similar to the following:
NQXB26JT1RKLP9VHarren Daggett B0BMAF00SSQ ME03B98TBAA8D
NBQB25KT1RKLP05Billison Whiner X0AMAF00UWE 8E21B98TBAF8W
...
...
...
Each string would process in series then loop to the next string, etc.
Strip out the name and the following strings:
Take the following 3 string fragments and convert to another number base. Have the code to process the new result but unsure of how to send these short strings to be processed in series.
QXB26
B0BM
BAA8
Then output the results to a file. The xxx represents the converted numbers.
xxxxxxxxx Harren Daggett xxxxxxxx xxxxxxxx
xxxxxxxxx Billison Whiner xxxxxxxx xxxxxxxx
...
...
...
The end result would be pulling parts of strings out of the first file and create a new file with the desired result.
There are several ways to accomplish what you are after, but if you want something simple and reasonably easy to debug, you could simply split up each record by the fixed position of each of the fields you have identified (the numbers, the name), then use a simple regular expression replace to condense the name and put it all back together.
For purposes like this I prefer a simple (and even a bit pedestrian) solution that is easy to follow and debug, so this example is not optimised:
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *URLs = [fm URLsForDirectory: NSDocumentDirectory
inDomains: NSUserDomainMask];
NSURL *workingdirURL = URLs.lastObject;
NSURL *inputFileURL = [workingdirURL URLByAppendingPathComponent:#"input.txt" isDirectory:NO];
NSURL *outputFileURL = [workingdirURL URLByAppendingPathComponent:#"output.txt" isDirectory:NO];
// For the purpose of this example, just read it all in one chunk
NSError *error;
NSString *stringFromFileAtURL = [[NSString alloc]
initWithContentsOfURL:inputFileURL
encoding:NSUTF8StringEncoding
error:&error];
if ( !stringFromFileAtURL) {
// Error, do something more intelligent that just returning
return;
}
NSArray *records = [stringFromFileAtURL componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
NSMutableArray *newRecords = [NSMutableArray array];
for (NSString *record in records) {
NSString *firstNumberString = [record substringWithRange:NSMakeRange(1, 5)];
NSString *nameString = [record substringWithRange:NSMakeRange(15, 27)];
NSString *secondNumberString = [record substringWithRange:NSMakeRange(43, 4)];
NSString *thirdNumberString = [record substringWithRange:NSMakeRange(65, 4)];
NSString *condensedNameString = [nameString stringByReplacingOccurrencesOfString:#" +"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, nameString.length)];
NSString *newRecord = [NSString stringWithFormat: #"%# %# %# %#",
convertNumberString(firstNumberString),
condensedNameString,
convertNumberString(secondNumberString),
convertNumberString(thirdNumberString) ];
[newRecords addObject: newRecord];
}
NSString *outputString = [newRecords componentsJoinedByString:#"\n"];
[outputString writeToURL: outputFileURL
atomically: YES
encoding: NSUTF8StringEncoding
error: &error];
In this example convertNumberString is a plain C function that converts your number strings. It could of course also be a method, depending on the architecture or your preferences.

Resources