How can I read bytes from a file in iphone application, chunk by chunk? - iphone

I am trying to implement an iphone application which can read some fixed amount of bytes from a file and store in another file. this process will go on up to the end of the file. I am very new to iphone application so please help me on that . Is there any parent classes out there for this specific type of implementation?

I had a very large file which couldn't be read with NSData methods, so I used the following (per TechZen's suggestion for fine grain control).
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
[fileHandle seekToFileOffset:offset];
NSData *data = [fileHandle readDataOfLength:length];

If you just want to copy the file, use NSFileManager's copy functions.
If you just want specific bytes in a file, you can load the file using NSData's file methods then you can get specific blocks of bytes and write them to file.
If you want more fine grain control, use NSFileHandler.
Edit01:
This page has examples for close to what you want. I don't have anything on hand.

Related

writing NSMutable array to plist file via writeToFile

I have a plist file called playerData that includes a number object at index 0 indicating the highest level completed. After loading the view I read this object's integer value that is used throughout the game logic. If the player wins the game I would like to increment this number and write it to the plist file. here is the code I have (contained in an if statement)
levelNumber++;
NSNumber *levelNSNum = [[NSNumber alloc] initWithInteger:levelNumber];
[playerData replaceObjectAtIndex:0 withObject:levelNSNum];
[playerData writeToFile:[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:#"PlayerData.plist"] atomically:YES];
NSLog(#"%i should be written to file", levelNumber);
the log works so I know the conditions of the if statement have been met and the value is not the same as the one that was previously in the plist file, but for some reason this data is not being written over that data.
I am relatively new to this so I could be making an easy, stupid mistake I just can't seem to track down an answer. Thank you for your help!
You're trying to write to your bundle, which is read-only after the app is installed. You should write to somewhere in your app sandbox instead, such as in your Library/Application Support directory. (You can use - [NSFileManager URLsForDirectory:inDomains:] with NSApplicationSupportDirectory to find this path; be sure to create the directory before you try to write to it.)

a long long file reading

I want to read one text file and perform some action on that data.
file size is 67 mb
how can i read.
file is in text format.
its working in simulateor but giving memory warning in device and crashes.
code is
NSString *content = [[[NSString alloc] initWithContentsOfFile:fileName usedEncoding:nil error:nil] autorelease];
crashes when this sentence complete.
Thanks,
Shyam parmar
You haven't given code, but if you are using stringWithContentsOfFile to get an entire file consider using NSInputStream or stdio to read it and process or display it more incrementally.
Fasttracks, try what Peter suggested. The problem is loading it all at once, since you have about 20 MB available for your own app, i believe. If you'd use a NSInputStream, you can load it in pieces, due to which you wont fill up the entire memory at once. Also read this answer to another question: Objective-C: Reading a file line by line
Do you start reading the file from - (void) viewDidLoad? That might be the problem. Try start reading it in a different thread, like: [self performSelectorInBackground:#selector(method) withObject:nil];

iPhone/iPad Base64->NSData->PDF how to?

Obj-C or Monotouch.Net C# answers are fine.
I have a Base64 string that is a PDF document received over a web service. I can get the NSData.
How do I take the NSData and save it as a PDF?
-- I get the NSData this way --
byte[] encodedDataAsBytes = System.Convert.FromBase64String (myBase64String);
string decoded = System.Text.Encoding.Unicode.GetString (encodedDataAsBytes);
NSData data = NSData.FromString (decoded, NSStringEncoding.ASCIIStringEncoding);
The simplest way to save it is probably to use NSData's writeToFile:options:error: method.
I found that using the .NET framework works better than trying to use the iOS framework for this problem. This will take any file and convert it to it's original then save it to the iPhone/iPad device. "path" is just a folder on the dev ice.
using (var f = System.IO.File.Create (path))
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String (Base64PDFString);
f.Write (encodedDataAsBytes, 0, encodedDataAsBytes.Length);
}
I'm working on a project where I recently had to accomplish the same thing you are describing. I get base64 encoded PDF files as strings from a .NET web service which need to be decoded to their original and saved as PDF files in the applications documents directory.
My solution was:
Use ASIHTTPRequest to communicate with the web service.
I then use TBXML to parse incoming xml and get the base64 as an NSString.
To decode the string I use a method from QSUtilities library called decodeBase64WithString.
Finally I save the result with NSData's writeToFile.
I have tested and successfully used this method with PDF files that are up to 25mb. I also had a couple of test runs with a 48mb file but that file made the decodeBase64WithString method take up too much memory and my app crashed. Haven't found a solution to this yet..
If you are working with multiple large files be sure to free up your memory once in a while. I got all my files in one loop in which I had to use my own nsautorelease pool and drain it at the end of the loop to free up any autoreleased objects.

using plist in iphone programming

I've read up Apple's documentation of plist: http://developer.apple.com/library/mac/documentation/cocoa/Conceptual/PropertyLists/PropertyLists.pdf
However I've got a few questions about it:
1) When we use the [dict writeToFile:plistPath atomically:YES] API, does it overwrite the current content of the plist? It doesn't say anything in the documentation.
2) Are we supposed to actually make the plist manually in Xcode by new file->resources->property list? Or are we supposed to have this:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSData *xmlData = [NSPropertyListSerialization //... a very long line here
if([fileManager fileExistsAtPath:plistPath]) {
[xmlData writeToFile:plistPath atomically:YES];
}
else {
[fileManager createFileAtPath:plistPath contents:xmlData attributes:nil];
}
3) How do we check if we've actually written data to property list? I tried products -> myapp.app -> "reveal in finder" -> right click -> show package contents, and there are some plists there, but I can't see the data being written! Is that mean I'm failed writing data to plist?
EDIT: Thanks everyone! Sorry for being silly today!
From the description of writeToFile:atomically:
If flag is YES, the dictionary is written to an auxiliary file, and then the auxiliary file is renamed to path. If flag is NO, the dictionary is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.
Since it is written to an auxiliary file and then renamed to the specified path, I would assume that it overwrites the current content of the file.
You should use the NSFileManager to find the application's documents directory and write the plist there. You should not use a resource, as you are going to write to it during the course of executing the app.
Add some logging (e.g., NSLog(#"plist path: %#", plistPath);) to show where the plist is getting written.
1) It will overwrite the current content. If you want to append some more data to your current plist file, first read it to a dictionary and add the data and write it back.
2) You can add it manually or create it programmatically.
3) Just log the contents of the plist file after writing.

How do I read a big SQL query string from a file?

I'm writing a database project on the iPhone and I'd like to store some big SQL queries in a separate, project-included file.
Then, I'd like to read this query into an NSString * (or, well, const char * is also ok) reference, and then perform it with an sqlite3.
I'm a newbie to iPhone developing, and I have never worked with files, neither I know any details of their storage.
Could you please give me a hint on:
The appropriate file format to store the strings.
How do I store it into the iPhone;
How do I read from it.
Thanks a lot!
You can use:
Any simple character based (text) file would be more than enough
Just put it in a folder in your project, it will get deployed with your Application
Use NSString class.
For issue #3 you can use:
NSString *sqlString =
[NSString
stringWithContentsOfFile:#"yourqueryfile.sql"
encoding:NSUTF8StringEncoding
errors:nil //unless yuo are interested in errors.
];