views:

45

answers:

2

Hey, Is it correct to initialize an NSData with a zip file? I want to convert a zip file into NSData and construct another file with the data (in simple language 'copy it'). I have the code as:

NSURL *theFileUrl = [NSURL URLWithString: @"file://localhost/Users/xxx/Desktop/testZippedFile.zip"];

NSData *data = [NSData dataWithContentsOfURL: theFileUrl];

When I, NSLog(@"Data: %@", data) , i do get some output but when I try to initialize an NSString with this data, it doesn't work:

 NSString *str = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
`NSLog(@"String: %@", string)`

I get the log as: String: PK

Can anyone point out my mistakes please. Thanks in advance!

+4  A: 

Why do it that way? NSFileManager will do it for you :)

[[NSFileManager defaultManager] copyItemAtPath:oldPath toPath:newPath error:nil];

However, this only works for files that are local - if you want to copy a file from a server, you should have a look at NSURLConnection to load the data and then NSData's writeToFile:atomically: method to save the contents to the file system (found here.)

deanWombourne
thanks! so could i use this to copy a file from a server onto the device then???
Bangdel
Hey, i'm testing my code in the simulator. I tried copyItemAtPath: for where both source and destination files are on the local machine and it worked perfectly fine. But when I set the source path as some URL say "http://someServer/someDirectory/zippedFile.zip", it gives an error : No such file or directory. Could you please tell me what is going wrong here?
Bangdel
You can't use this to copy from a server to your device - I assumed that you just wanted to move a file around after you had downloaded it. See my edit for other solutions
deanWombourne
Bangdel
it works ok...but i think i'll have to work on the NSURLConnection thing... Thanks a lot!
Bangdel
+1  A: 

PK is the output you should expect.
The first 2 Characters in every zip-file are PK. Then there are some unprintable chars and at some point after those there is a character with a value of 0
If you create an NSString out of NSData all values up to the first 0-value are taken into account.

NEVER convert binary data into NSString.

fluchtpunkt
k i'll keep that in mind
Bangdel