How to save multiple files in bundle in iphone app? - iphone

Hi all i am trying to save image in the bundle which i have currently on my view,but the problem is that i can only save one image,if i want to save the another image it replaces the old.I am not getting how to save the multiple images in the bundle then.
Here is my code.
- (void)writeImageToDocuments:(UIImage*)image
{
NSData *png = UIImagePNGRepresentation(image);
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError *error = nil;
[png writeToFile:[documentsDirectory stringByAppendingPathComponent:#"image.png"] options:NSAtomicWrite error:&error];
}
Please Help me out, how to save multiple images, files e.t.c in bundle
Thanks in advance

You're not saving into a bundle, you're saving into your app's documents directory. There's no bundle aspect to it.
You're using the filename #"image.png" for every file that you save. Hence each new write overwrites the old one. In fact, you write each file twice. To save multiple files, use different file names.
It's also bad form to pass a numeric constant as the 'options:' parameter of NSData writeToFile:options:error: (or indeed, any similar case). The value '3' includes an undefined flag, so you should expect undefined behaviour and Apple can legitimately decline to approve your application. Probably you want to keep the NSAtomicWrite line and kill the one after it.
If you're just looking to find the first unused image.png filename, the simplest solution would be something like:
int imageNumber = 0;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathToFile;
do
{
// increment the image we're considering
imageNumber++;
// get the new path to the file
pathToFile = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat:
#"image%d.png", imageNumber]];
}
while([fileManager fileExistsAtPath:pathToFile]);
/* so, we loop for as long as we keep coming up with names that already exist */
[png writeToFile:pathToFile options:NSAtomicWrite error:&error];
There's one potential downside to that; all the filenames you try are in the autorelease pool. So they'll remain in memory at least until this particular method exits. If you end up trying thousands of them, that could become a problem — but it's not directly relevant to the answer.
Assuming you always add new files but never remove files then this problem is something you could better solve with a binary search.
File names searched will be image1.png, image2.png, etc.

Related

Objective-C: Create text file on device and easily retrieve the file

I am wanting to write my own logs to a text file on my iPhone. I wrote up a quick method that writes a string to a file. Right now it saves it into the Documents directory, which, if on the device is going to be a pain to get off, since I can't just browse to it. Is there a better way to quickly get this file off the device after I have written to it?
/**
* Logs a string to file
*
* #version $Revision: 0.1
*/
+ (void)logWithString:(NSString *)string {
// Create the file
NSError *error;
// Directory
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"log.txt"];
// Get the file contents
NSData *localData = [NSData dataWithContentsOfFile:filePath];
if (localData) {
NSString *logString = [[NSString alloc] initWithData:localData encoding:NSUTF8StringEncoding];
string = [logString stringByAppendingFormat:#"%#\n", string];
[logString release];
}
// Write to the file
[string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
}//end
Add Application supports iTunes file sharing to your application target's build info in Xcode:
Then, you can easily browse, retrieve and delete any files created by the app from iTunes, right under Devices > Your device > Apps > File Sharing:
You may have to capture what number of logs you have created so far and create a new name for each log biased on that.
So you might save your last made logs name as a string in NSUserDefaults and get the number off the end of that and add one onto that captured int ready for the next name.
So if you have #"Log4" you can get the 4 out of that and make it 5 so that the next log is named "Log5"
Just my 2 cents :P
With regard to the 'How to get the file' part of the question
iExplorer, previously iPhone Explorer allows you to view your apps, including their documents folder without jailbreaking your devices.
In my experience (albeit of an older version), getting the files from the phone can be a little temporamental (i.e. I drag a file onto my desktop and although it creates the file, it doesn't write any of the data), you can get the files from your device.

fileExistsAtPath API always return NO

Following is my code I need check whether file present in document directory ,But following API does not return true at any condition but file is get created in document directory. Please check any thing wrong I am doing. I have searched on this other says this API "fileExistsAtPath" should work but it is not working in my case. Please do help me.
NSString *recordFile=[NSString stringWithFormat:#"MyFile.acc",data.uid];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDr = [documentPaths objectAtIndex:0]; // WHY 0 ?
NSString *uniquePath = [documentDr stringByAppendingPathComponent:recordFile];
if([[NSFileManager defaultManager] fileExistsAtPath: uniquePath])
{
NSLog(#"File found")
}
else {
NSLog(#"No File to play");
}
Thanks,
Sony
Probably your path is incorrect. What should be the name of the files you are trying to find? If you have #"MyFile1.acc", #"MyFile2.acc" etc (where 1, 2 is the data.uid value) then try to use this:
NSString *recordFile=[NSString stringWithFormat:#"MyFile%i.acc",data.uid];
Try to append a "/" after documentDr when define uniquePath, or
NSString *recordFile = [NSString stringWithFormat:#"MyFile%#", data.uid];
...
if([NSBundle pathForResource:recordFile ofType:#"acc" inDirectory:documentDr])
the first wrong thing i note is the first instruction.
Why do you pass 'data.uid' as an argument to the format string ? Assuming 'data.uid' is some kind of integer, there should be at least '%d' in...
I had a look to Apple Documentation, in particular, that statement which says
The directory returned by this method may not exist.
You could try getting the current directory path using NSFileManager methods, and then testing for file existence (or create a directory at a place you can easily retrieve later).
What about the others paths ? You wrote 'WHY 0 ?', i'm asking the same question as you.Try looping over the array elements, testing each time for file existence.
The code should work. Your file most likely doesn't exist. Did you use capitalisation in your file name right when saving it?
Also right now, I still don't know what the file name is since, as already said, the first line in your initial post doesn't give the format string right.
Before checking try for existance try:
[[NSString stringWithString:#"test"] writeToFile: uniquePath atomically:YES];
That should create a file at the path and you see, that fileExists works.
I tried many things but ended up that I had to delete the app, clean all targets, and then rebuild again. It's weird that somehow my new resources doesn't get copied to the app. It usually happens to files that when I added them I selected "Create folder references for any added folders".

Locally saved data files are persistant in the emulator but not in the real iPad device... I'm lost

I'm a (kind of) newbie XCode programmer (well, I would say not so newbie nowadays...) and "my pet issue" is: "I'm having trouble saving local files onto my real iPad, compared to saving them with the simulator".
Well to be honest, I have no problem whatsoever SAVING local files, but retrieving them. Why? Because on the simulator my local files seem to persist between compilation sessions, but on the real device, every time the application gets launched (not only after being uploaded from Xcode, but normally launched), data inside the "Documents" directory seems to disappear... So the final user would not be able to store needed historical data between sessions.
Is it a perception of mine? Is it normal behaviour?
The code I use to save this "persistent" data is this one:
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDir = [paths objectAtIndex:0];
NSString *finalPath=[NSString stringWithFormat:#"%#/%#", documentsDir, path];
NSLog(#"Course.m: updatePersistentObject (to disk): final file = %#",finalPath);
[NSKeyedArchiver archiveRootObject:newObject toFile:finalPath];
'path' variable being #".HistoricalTestResults";
The code I use to retrieve data (wheather at boot time, or at runtime) is this one:
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#" historical data: Documents paths = %#", paths);
NSString * docsDir = [paths objectAtIndex:0];
NSLog(#"Course.m: loadHistoricalResultsData: docsDir vale [%#]", docsDir);
NSString *tmpPath=[NSString stringWithFormat:#"%#/.HistoricalTestResults", (NSString *)docsDir];
NSLog(#"Course.m: loadHistoricalResultsData: tmpPath vale [%#]", tmpPath);
NSFileManager *localFileManager = [[NSFileManager alloc] init];
// create directory if it doesn't exist, don't do anything if it exists... (?)
[localFileManager createDirectoryAtPath:tmpPath withIntermediateDirectories:YES attributes:nil error:nil];
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:tmpPath];
NSString *file;
while (file = [ dirEnum nextObject])
{
NSLog(#"Historical Data Folder: %#", file);
if ( [[file pathExtension] compare:#"dat"] == NSOrderedSame )
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", tmpPath, file];
NSLog(#"Course.m: loadHistoricalResultsData: filePath vale [%#]", filePath);
mHistoricalTestList=[[NSKeyedUnarchiver unarchiveObjectWithFile:filePath] retain];
}
}
[localFileManager release];
My exact problem is that while on the simulator, AT BOOT TIME, if I put a trace on the "while" code line, I can see how the enumerator gets some value, and I can iterate among the found files.
On the other hand, when using my iPad, the same breakpoint yields a "nil" pointer when obtaining the enumerator.
As I said, at the beginning of a clean program session, this is normal, so then I need to generate some storable results inside my program memory to store them onto disk.
I do it, and then I write them (both inside the simulator and the iPad). Then I can even re-retrieve this data (from disk) and it seems to still exist inside the Documents folder (both onto the iPad and the simulator).
But then, if I close/kill the program, this data seems to be lost onto the real iPad, and to persist in the simulator.
With this behaviour, my only deduction is "Real iPad programs cannot store persistent data onto their Documents directory". Am I right? (Of course not, because I've seen it work on some other programs).
So I have the feeling I'm doing something wrong, and after wasting TONS of time trying to find it, I'm now asking for advice on stackoverflow...
Every piece of help/insight/hint will be more than welcome.
Something I can think of is that your app is not being installed on the same app sandbox everytime. That means that while in the simulator your path is the same and the documents dir contains the same data, your ipad creates a new directory path for the installation, therefore the data you persisted in the last session won't be accessible.
Another thing that I experienced, was that the simulator was case insensitive when loading up resources, in contrast with the device that is actually case sensitive. In that time I had a strings file with extension .Strings and the iphone was looking for .strings. The simulator would work but the phone showed the keys when LocalizedString() macro was called.
So, tl;dr: verify the paths are the same in the different sessions, and your file names match.
I hope it helps. good luck!
PS: Gaudí rlz.
I'm happy! I was able to solve my own mess (!!?).
I've discovered that, when I originally copied my 2 code snippets, specially the "read part", I didn't copy it literally as it appears on my actual code, I just adapted some variable names and extra stuff that wasn't important here. (Typical situation)
I even did some more things than "removing some unrelated code pieces", (and here comes the important part), as I reordered some of them. And one of the parts I reordered was this one (which didn't work):
NSFileManager *localFileManager = [[NSFileManager alloc] init];
NSString *tmpPath=[NSString stringWithFormat:#"%#/.HistoricalTestResults", (NSString *)docsDir];
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:tmpPath];
// create directory if it doesn't exist, don't do anything if it exists... (?)
[localFileManager createDirectoryAtPath:tmpPath withIntermediateDirectories:YES attributes:nil error:nil];
which I changed (when posting here), onto this other part (which works):
NSString *tmpPath=[NSString stringWithFormat:#"%#/.HistoricalTestResults", (NSString *)docsDir];
NSFileManager *localFileManager = [[NSFileManager alloc] init];
// create directory if it doesn't exist, don't do anything if it exists... (?)
[localFileManager createDirectoryAtPath:tmpPath withIntermediateDirectories:YES attributes:nil error:nil];
NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:tmpPath];
There's proably some logic behind this, as "why the first part does work on the emulator, but doesn't on the real device". It seems that "createDirectoryAtPath" is somewhat "resetting" some internal stuff, or maybe asking for an enumerator without having created a directory doesn't make sense...
Whatever the case is, I think my experience is worth enough to keep it here posted for someone who might be in my situation in the future!
Greetings again!

How to store recorded file in array?

Here is the code that i save audio file in string. After that i add in array. But still not work here..
Is there any options here to store audio file in array after that storing documentdictionary.
fileArray = [[NSMutableArray alloc] initWithContentsOfURL:recordedTmpFile];
fileArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [fileArray objectAtIndex:0];
NSMutableDictionary *recordDictionary = [NSDictionary dictionaryWithContentsOfFile:documentsDirectory];
NSFileManager *fileManager = [NSFileManager defaultManager];
for(int i= 0; i<fileArray.count;i++)
{
NSString *recorded = [fileArray objectAtIndex:i];
NSString *filePath = [recordDictionary stringByAppendingPathComponent:recorded];
newArray = [fileManager fileExistsAtPath:filePath];
}
If any code missing by me than suggest me some specific idea about.
Plz give some response..
I don't want to sound like a dick, but just throwing code at an editor isn't going to work. I don't often write answers like this, but sometimes it needs to be done;
Here's a line-by-line breakdown of what you have written and maybe that will give you an idea of what this snippet is doing:
You create an NSMutableArray called fileArray initialised with the contents of a file. I don't know whether this file is in the correct format or not. documentation
You then overwrite this array with an array of search paths. Incidentally, you've now leaked the memory of the initial array.
You get a string to the Documents directory.
You try to create an NSDictionary from a string rather than in the specific format required by the message. As this is an invalid file recordDictionary is nil documentation
You create a reference to the FileManager
You start a for loop to iterate the contents of fileArray
You get each item in fileArray but this is only a list of directories, not files (see point 2)
You try and create a filePath by appending what you think of as a file to a directory except you are appending a directory (see point 7) to nil (see point 4)
You declare an undimensioned variable and try to assign a BOOL to it documentation
So you've written a lot of code that doesn't do anything. It doesn't work because I doubt you have tried to compile it.
Looking at your question history it seems you ask the same question over and over again. You would be better off starting with a basic introduction to Cocoa and working through that until you understand why your code snippet is so wrong.
All you need to do is to get the location of the file you want to save, and move it to the correct place. Somebody else may just write your code for you, but I won't - I'm not that desperate for the points and I'll just be doing you a disservice. Go back to basics, ask specific questions with some idea of what you've tried and you'll get a far better response

Is possible to read plist from application bundle and documents folder at the same time?

Is it possible?to read from my local bundle and at the same time also read from documents folder into UItableview?
thanks thanks
yes.simultaneously
No — as in the iPhone isn't multicore, you can't have "simultaneous" :p
Yes — as in you can open multiple files in the same period of time. There's no conflicts as long as the files are different (if the files are the same then it depends on how others are using and locking the file etc.)
on viewDidLoad or some similar event when you would be populating your table data, you would simply just aggregate the two files together... that is you are are likely populating an array or dictionary with the contents of the file in question... so use the mutable version of array/dictionary, initialize it empty, then read in the first file from whatever location you choose, populating into your mutable array/dictionary, then do the the same for the next file. after you are done, reloadData as you normally would as if you had read form one file.
As far as simultaneous goes, technically no. However, one could have two different active threads each one reading required files and parsing the data.
Regarding the files you want to access...
Here is a quick and dirty method I use in one project (which I just happen to be working on at the moment):
NSFileManager* fileManager = [NSFileManager defaultManager];
NSError* error;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
self.documentsDirectory = [paths objectAtIndex:0];
self.blahDBPath = [self.documentsDirectory stringByAppendingPathComponent: #"blah.db"];
NSLog(#"Mainbundle Resourcepath: %#", [[NSBundle mainBundle] resourcePath]);
NSString* defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"blah.db"];
NSLog(#"Default DB Path: %#", defaultDBPath);
success = [fileManager copyItemAtPath:defaultDBPath toPath:self.blahDBPath error:&error];
if (!success) {
NSAssert1(0, #"blah blah blah '%#'.", [error localizedDescription]);
}
It is ugly but effective. I'll rewrite it when I refactor the application.
The point here is that I ask the operating system for the path to certain directories. Then I add file names or subdirectories as required. This allows the operating system to manage paths (like in the simulator where each successive build gets a new unique id as part of its path) and I just worry about the final directories and file names in the application.
One I have the paths, I copy the required file from the bundle directory and put them somewhere, the Documents directory in this case. Then I can do whatever I need to with them.
If I just wanted to access them as they are in the bundle directory, then I I just refer to them by using [[NSBundle mainBundle] resourcePath].
I think something along the lines of the above snippet is what you are looking for.
-isdi-