Download binary file to documents directory (IOS). How? - ios

I want to store a binary file in my IPad-Documents-Directory.
- (void) connectionDidFinishLoading:(NSURLConnection *) connection
NSString *txt = [[[NSString alloc] initWithData:responseData encoding: ?????] autorelease];
//write to disk
file = ...;
[txt writeToFile:file atomically:NO encoding:??? error:NULL];
So, now I get a binary file, that is different from the original one. I assume, it is the encoding or Bigendian / LittleEndian;
If I use an Ascii-File this method works without any problem.
What should I do? Not using NSString? What encoding? Tried severals. None worked.
Any Idea?

You can (and should) save NSData object directly to the disc without converting it to NSString:
[responseData writeToFile:file atomically:NO];

You are storing binary data in an NSString object and writing it out to the file system, while instead I think you should load that binary data into an NSData object and then say:
[myNSDataObject writeToFile:myFilePath atomically:YES];

Related

Generate a ppt file with byte array/NSData, in objective c?

I have a NSData value, generated from a byte array response. Now I need to save this as a .ppt file in iPhone/iPad, I learned from this link that there is no way to directly do it.
I already tried saving it as a PDF first, but failed in that too, since I'm unable to reproduce the charts from the nsdata.
Now is there another way to get this done other than sending the file through mail associated to the device?
Please do give out only the ways by which I can carry this out in the background without the help of the user? Any help will be appreciated.Thanks
I got it working, tried a lot but nothing worked and finally ran into some random code blocks, using which I got this wonderful piece of code,
//--------------------------------------------------------------------------------generating input URL
NSString *urlAddress = #"url containing the pdf data";
NSURL *theRessourcesURL = [NSURL URLWithString:urlAddress];
//--------------------------------------------------------------------------------defining file location details & writing a ppt file with a name "new.ppt"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathFloder = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%#",#"new.ppt"]];
NSString *defaultDBPath = [documentsDirectory stringByAppendingPathComponent:pathFloder];
NSData *tmp = [NSData dataWithContentsOfURL:theRessourcesURL];
[tmp writeToFile:defaultDBPath atomically:YES];

CSV to NSString results in empty null object

I'm trying to retrieve content of a csv file to NSString. Thats what I do:
NSString *strBundle = [[NSBundle mainBundle] pathForResource:#"socs" ofType:#"csv"];
NSLog(#"bundle path: %#",strBundle);
NSString *file = [NSString stringWithContentsOfFile:strBundle
encoding:NSUTF8StringEncoding
error:nil];
if ([[NSFileManager defaultManager]fileExistsAtPath:strBundle]) {
NSLog(#"file is there!!!");
}else {
NSLog(#"no file");
}
NSLog(#"file: %#",file);
NSArray *allLines = [file componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSLog(#"lines: %lu",(unsigned long)[allLines count]);
file manager shows that the file is there. When i try to log the NSString or number of files it says null. I even created NSData object with the content of exactly the same file and when I logged the NSData object, I clearly saw that there is some data. Then when I tried to create NSString with the content of NSData, I had the same result as before - null. Maybe the problem is somewhere in the formatting of the file?
Any help will be appreciated :)
I see 3 issues:
You are passing a nil argument to the error: parameter in your stringWithContentsOfFile: line. If there's a possibility something might go wrong (and apparently there is), you should pass a real argument there so you can figure out what went wrong.
You can use componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet], but that has a tendency to produce blank "components" between every line. Plain old #"\n" works better in virtually all cases I've run into.
You should be checking fileExistsAtPath before you try to load it into the NSString
If you were truly able to create an NSData object from the path it doesn't necessarily mean it's correct data. But let's say it is, if you were not able to convert it to a NSString then you need to check your encoding parameter.

iOS: read raw plist

I want to read the UserDefaults plist but not as Dictionary or Data. I want it as string like it is when you open it with an editor.
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *homeDir = [documentsPath stringByReplacingOccurrencesOfString:#"Documents" withString:#""];
NSString *defaultsPath = [homeDir stringByAppendingString:[NSString stringWithFormat:#"Library/Preferences/%#.plist", [[NSBundle mainBundle] bundleIdentifier]]];
NSData *data = [NSData dataWithContentsOfFile:defaultsPath];
Already tried:
`NSString *contents = [NSString stringWithContentsOfFile:defaultsPath encoding:NSUTF8StringEncoding error:&error];
which ends up with
The operation couldn’t be completed. (Cocoa error 261.)
Property list formats can be either binary or text. Binary plists can't be loaded into an NSString because strings are for text, not arbitrary binary data. The error you're getting seems to suggest that the file cannot be interpreted as UTF-8, which either means it is encoded using another encoding or is not text at all.
If you are certain that the property list is a text property list, you can use:
NSStringEncoding enc;
NSString *contents = [NSString stringWithContentsOfFile:defaultsPath usedEncoding:&enc error:&error];
This will allow the framework to determine the encoding of the text plist for you. If it isn't a text plist, you can convert it to one using the plutil command line utility:
plutil -convert xml1 file.plist
Or, alternatively you can do this in code by loading the plist using the NSPropertyListSerialization class, obtaining the NSData from it that represents the plist as the XML format, and then convert that to a string.
An example would be [uncompiled and untested]:
// load the file as-is into a data object
NSData *data = [NSData dataWithContentsOfFile:defaultsPath];
// convert the plist data into actual property list structure
id plistFile = [NSPropertyListSerialization propertyListWithData:data
options:0
format:NULL
error:&error];
// get the XML representation of the property list
NSData *asXML = [NSPropertyListSerialization dataWithPropertyList:plistFile
format:NSPropertyListXMLFormat_v1_0
options:0
error:&error];
// convert the NSData object into an NSString object
NSString *asString = [[NSString alloc] initWithData:asXML encoding:NSUTF8StringEncoding];
This should work whether the original plist is in XML or binary format. In this example, I am assuming that the XML representation of the property list is in fact UTF-8 encoded, as this is the most common encoding for XML data.

Can I Archive NSData objects inside another NSData without corrupting data?

I have two NSData objects I want to store within a third NSData object. The idea is I want to make it easy when I later decode the larger object, to get at the two smaller objects independently of one another, without worrying about their relative sizes or datatypes.
It appears the best way to do this is to use NSKeyedArchiver to create a sort of root-level key-value structure within the larger NSData object, in which I can store the two smaller objects within separate keys. That's what I've attempted to do here:
NSData *data1Before = [#"abcdefgh" dataUsingEncoding:NSUTF8StringEncoding];
NSData *data2Before = [#"ijklmnop" dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *allData = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:allData];
[archiver encodeObject:data1Before forKey:#"key1"];
[archiver encodeObject:data2Before forKey:#"key2"];
[archiver finishEncoding];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:allData];
NSData *data1After = [unarchiver decodeObjectForKey:#"key1"];
NSData *data2After = [unarchiver decodeObjectForKey:#"key2"];
[unarchiver finishDecoding];
NSString *string1After = [NSString stringWithUTF8String:[data1After bytes]];
NSString *string2After = [NSString stringWithUTF8String:[data2After bytes]];
NSLog(#"after1: %#",string1After);
NSLog(#"after2: %#",string2After);
The problem is, when you run this code over and over, you get all sorts of different results coming from the NSLog statements- someetimes special characters get appended to the end of the strings, sometimes they're just NULL.
It appears this corruption has something to do with this "double-encoding" process I'm using. When I modify the code so that the NSKeyedArchiver just calls encodeObject directly on NSStrings, rather than on NSData objects, I can later use decodeObjectForKey and get at those strings without any problems- no corruption at all.
Is there a better way of doing this than using NSKeyedArchiver? Or am I using it incorrectly?
Thanks to rmaddy for his answer above- I just needed to replace this:
[NSString stringWithUTF8String:[data1After bytes]];
with this:
[[NSString alloc] initWithData:data1After encoding: NSUTF8StringEncoding];
and that fixed it.

convert UIImage to NSString - without using encoding & decoding

I want to convert the UIImage to NSString without using any encoding and decoding methods. Following code is used.. please guide me.. Here i have used "encoding:NSASCIIStringEncoding". But I don't want to use. I want to use the binary directly. is it possible ?
UIImage *image = [[UIImage alloc]initWithData:imageName];
NSData *imageDataString = UIImagePNGRepresentation(image);
NSString *content = [[NSString alloc]initWithBytes:[imageDataString bytes] length:[imageDataString length] encoding:NSASCIIStringEncoding];
Thanks in Advance.
If you would like to save it as a binary file, why don't you just use NSDatas writeToURL:atomically: method? If you don't want to save a file - just continue working with NSData. It is an objective-c wrapper around your raw binary data.

Resources