i am trying to read jpg file and convert into byte array
this is the following code this code works fine with text file but files on image files
// start code
NSString *stringFromFileAtPath = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if(stringFromFileAtPath == nil){
NSLog(#"Error reading file at path %#\n%#", path, [error localizedFailureReason]);
}
NSLog(#"Contents:%#", stringFromFileAtPath);
NSData *bytes = [stringFromFileAtPath dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Bytes:%#", bytes);
// end of code
and this is error message i am getting
Error Message:Text encoding Unicode (UTF-8) isn’t applicable.
Let me know what is the error i am doing or code to convert jpg file to byte array
Why not just use NSData's initWithContentsOfFile: method? See here:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html
i.e.:
NSData *bytes = [[NSData alloc] initWithContentsOfFile:path];
NSLog(#"Bytes:%#", bytes);
The reason you can't do what you did is that you're trying to read the image file as if it is encoded in UTF8, which it's highly likely there's bytes in there that would be malformed in UTF8 - it's not a string.
Related
I have NSData object,it contains 16300 bytes and I am writing to file. Write is success full. But once I want to read from path again, it gives me only 44 bytes.
//writing to path
[audioData writeToFile:recorderFilePath options:NSDataWritingAtomic error:&err];
if (err) {
NSLog(#"Error of writing to file %#",[err localizedDescription]);
}
// reading from path
NSData *paddata = [NSData dataWithContentsOfFile:filePath];
Any help will be appreciated.
Thank you.
Just below code used for write your audio file and read from path.
Write audio file to path
[fileData writeToFile:audioFilePath atomically:YES];
reading from path
NSURL *soundFileURL = [NSURL fileURLWithPath:audioFilePath];
I have an array that I serialize, encrypt and then write into a file. The data itself appears to be good but I'm having problems restoring the array back from the file. Here is what I do
NSString *filename = [[self getTransactionLogPath] stringByAppendingPathComponent:transactionLogName];
NSData *data = [[NSData alloc] initWithContentsOfFile:filename];
NSLog(#"encrypted data: %#", data);
EncryptedData *decoder = [[EncryptedData alloc] init];
NSData *decrypted = [decoder reverseTransformedValue:data];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:decrypted];
I get the filename and read the data from file. EncryptedData decoder runs AES128 on the data and finally I unarchive the array.
The problem is that unarchiveObjectWithData throws an exception
[NSKeyedUnarchiver initForReadingWithData:]:
incomprehensible archive
The tricky thing is that the code works fine in simulator if I keep the NSLog line i.e. I print out the data after reading the file.
On device the NSLog() does not help. Is this a threading problem where the unarchiver starts before the data is read?
I tried adding a delay instead of the NSLog() line but that didn't help.
Any other ways to do the job if I want to encrypt the array before writing to file?
So, I'm trying to open a .mobileprovisioning profile to read what's inside... this is what I'm doing:
NSString *path = [pathURL path];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
Of course I get the data read but I'm not finding the way of getting of get this data into something useful... an NSDictionary, an NSString or whatever...
I've already tried:
NSString *newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
Any idea? I'm sure this is an encoding issue, but I can't solve it after reading and googling for some time... I think the provisioning profile is saved as hexadecimal, but I don't know how to read that from objective-c. I have found this but there wasn't an useful answer.
How to convert NData populated with hex values to NSString
Thanks!
The following method should do what you want. As #rbrockerhoff says the mobile provisioning profile is an encoded CMS message. This method uses a decoder to first decode the data using the CMS functions and then creates the plist string/contents from the decoded data. This string can then be converted into a dictionary which is returned from the method. The dictionary will contain all the details from the mobile provisioning profile.
- (NSDictionary *)provisioningProfileAtPath:(NSString *)path {
CMSDecoderRef decoder = NULL;
CFDataRef dataRef = NULL;
NSString *plistString = nil;
NSDictionary *plist = nil;
#try {
CMSDecoderCreate(&decoder);
NSData *fileData = [NSData dataWithContentsOfFile:path];
CMSDecoderUpdateMessage(decoder, fileData.bytes, fileData.length);
CMSDecoderFinalizeMessage(decoder);
CMSDecoderCopyContent(decoder, &dataRef);
plistString = [[NSString alloc] initWithData:(__bridge NSData *)dataRef encoding:NSUTF8StringEncoding];
NSData *plistData = [plistString dataUsingEncoding:NSUTF8StringEncoding];
plist = [NSPropertyListSerialization propertyListWithData:plistData options:NSPropertyListImmutable format:nil error:nil]
}
#catch (NSException *exception) {
NSLog(#"Could not decode file.\n");
}
#finally {
if (decoder) CFRelease(decoder);
if (dataRef) CFRelease(dataRef);
}
return plist;
}
A .mobileprovisioning file is an encoded CMS message.
See https://developer.apple.com/library/mac/documentation/security/Reference/CryptoMessageRef/Reference/reference.html for details and an API for decoding it.
If you just want the encoded property list as text, a quick-and-dirty hack is to get the byte pointer for your NSData, scan for the beginning "<?xml" and up to the closing "</plist>". Then make a NSString from that.
You can simply force to open the mobile provisioning profile in TextEdit where you can see the
interior contents and in which you can trim/Edit the encoded CMS message or whatever you want . Then you can simply decode with NSData encodewithUTF string method.
Hope this helps.
I building a Mac app,I have 2 problem:
I want to create a text file to read and write data on it. I don't know how to crate a text file to read and write data. Is it use
struct?
I want to create a XML file to read and write data on it. Can I create a struct for XML?
Do you have suggestion? Thanks in advance
Well, to create a file, just use
[[NSFileManager defaultManager] createFileAtPath:#"Your/Path" contents:nil attributes:nil];
This creates an empty file, which you can write to or read from. To write text (or XML), just use NSString's writeToFile:atomically:encoding:error: method like this
NSString *str = //Your text or XML
[str writeToFile:"Your/Path" atomically:YES encoding:NSUTF8StringEncoding error:nil];
To read from a file, just make an NSString with the contents of that file
NSString *contents = [NSString stringWithContentsOfFile:#"Your/Path"];
or, if it does not contain a string, get an NSData object from the file
NSData *contents = [NSData dataWithContentsOfFile:#"Your/Path"];
/**************************main.m******************************
NS FILE HANDLE READ & WRITE
reading and writing in same file
Created by abdulsathar on 6/16/14.
***************************************************************/
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool //ARC
{
NSFileHandle *file;
//object for File Handle
NSError *error;
//crearing error object for string with file contents format
NSMutableData *writingdatatofile;
//create mutable object for ns data
NSString *filePath=[NSString stringWithFormat:#"/Users/chandrakumar/Documents/abdul/doc.txt"];
//telling about File Path for Reading for easy of access
file = [NSFileHandle fileHandleForReadingAtPath:#"/Users/chandrakumar/Documents/abdul/doc.txt"];
//assign file path directory
if (file == nil) //check file exist or not
NSLog(#"Failed to open file");
NSString *getfileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
//access file contents with out ns handle method
if (error) //check error flag for file present or not
NSLog(#"Error reading file: %#", error.localizedDescription);
NSLog(#"contents: %#", getfileContents);
//display file contents in main file
NSArray *listArray = [getfileContents componentsSeparatedByString:#"\n"];
//caluculate list of line present in files
NSLog(#"items = %ld", [listArray count]);
const char *writingchar = "how are you";
writingdatatofile = [NSMutableData dataWithBytes:writingchar length:strlen(writingchar)];
//convert string format into ns mutable data format
file = [NSFileHandle fileHandleForUpdatingAtPath: #"/Users/chandrakumar/Documents/abdul/new.txt"];
//set writing path to file
if (file == nil) //check file present or not in file
NSLog(#"Failed to open file");
[file seekToFileOffset: 6];
//object pointer initialy points the offset as 6 position in file
[file writeData: writingdatatofile];
//writing data to new file
[file closeFile];
//close the file
}
return 0;`enter code here`
}
/***********************************OUTPUT********************************************
2014-06-17 14:55:39.695 storage[4075:303] contents: hello how are you my dearservice
*************************************************************************************/
I'm trying to combine images in my app into one file and write it to disk.
NSMutableArray *array = [NSMutableArray arrayWithObjects:
[NSData dataWithContentsOfFile:#"0.png"],
[NSData dataWithContentsOfFile:#"1.png"],
[NSData dataWithContentsOfFile:#"2.png"],
nil];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
NSError *error = nil;
NSString *path=#"/Users/myusername/Desktop/_stuff.dat";
[data writeToFile:path options:NSDataWritingAtomic error:&error];
or
NSArray *array = [NSArray arrayWithObjects:
[NSImage imageNamed:#"0"],
[NSImage imageNamed:#"1"],
[NSImage imageNamed:#"2"],
nil];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
NSError *error = nil;
NSString *path=#"/Users/myusername/Desktop/_stuff.dat";
[data writeToFile:path options:NSDataWritingAtomic error:&error];
But both produce a file that is 4KB (empty). If I NSLog the error it is (null). Am I making the data the wrong way?
Edit: If I open the resulting file with a text editor, it looks like this:
I wrote a quick example:
Missing: memory management / error handling / proper file handling
// Archive
NSMutableArray *array = [[NSMutableArray alloc] init];
NSString * input = #"/Users/Anne/Desktop/1.png";
[array addObject:[NSData dataWithContentsOfFile:input]];
[array addObject:[NSData dataWithContentsOfFile:input]];
[array addObject:[NSData dataWithContentsOfFile:input]];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
NSString *path = #"/Users/Anne/Desktop/archive.dat";
[data writeToFile:path options:NSDataWritingAtomic error:nil];
// Unarchive
NSMutableArray *archive = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSData * firstObject = [archive objectAtIndex:0];
NSString * output = #"/Users/Anne/Desktop/2.png";
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:output];
[firstObject writeToURL:fileURL atomically:YES];
You can also add NSImages to the NSMutableArray:
NSString * input = #"/Users/Anne/Desktop/1.png";
NSImage *image = [[NSImage alloc] initWithContentsOfFile: input];
[array addObject:image];
But that will significantly increase the file size.
Response to the following comment:
So if I only need to access an image at runtime (in the archive), is there a way to access that image at an index without unarchiving the whole thing? Seems like unnecessary overhead to me.
I assume you're still struggling with this problem?
Hiding (or encrypting) app resources?
Like i mentioned earlier, combining all files into one big file does the trick.
Just make sure you remember the file-length of each file and file-order.
Then you can extract any specific file you like without reading the whole file.
This might be a more sufficient way if you only need to extract one file at the time.
Quick 'dirty' sample:
// Two sample files
NSData *fileOne = [NSData dataWithContentsOfFile:#"/Users/Anne/Desktop/1.png"];
NSData *fileTwo = [NSData dataWithContentsOfFile:#"/Users/Anne/Desktop/2.png"];
// Get file length
int fileOneLength = [fileOne length];
int fileTwoLength = [fileTwo length];
// Combine files into one container
NSMutableData * container = [[NSMutableData alloc] init];
[container appendData:fileOne];
[container appendData:fileTwo];
// Write container to disk
[container writeToFile:#"/Users/Anne/Desktop/container.data" atomically:YES];
// Read data and extract sample files again
NSData *containerFile = [NSData dataWithContentsOfFile:#"/Users/Anne/Desktop/container.data"];
NSData *containerFileOne =[containerFile subdataWithRange:NSMakeRange(0, fileOneLength)];
NSData *containerFileTwo =[containerFile subdataWithRange:NSMakeRange(fileOneLength, fileTwoLength)];
// Write extracted files to disk (will be exactly the same)
[containerFileOne writeToFile:#"/Users/Anne/Desktop/1_extracted.png" atomically:YES];
[containerFileTwo writeToFile:#"/Users/Anne/Desktop/2_extracted.png" atomically:YES];
// Only extract one file from the container
NSString * containerPath = #"/Users/Anne/Desktop/container.data";
NSData * oneFileOnly = [[NSFileHandle fileHandleForReadingAtPath:containerPath] readDataOfLength:fileOneLength];
// Write result to disk
[oneFileOnly writeToFile:#"/Users/Anne/Desktop/1_one_file.png" atomically:YES];
Tip:
You can also save the 'index' inside the container file.
For example: The first 500 bytes contain the required information.
When you need a specific file: Read the index, get the file position and extract it.
You are archiving a NSMutable array of NSImage. This two classes conform to the NSCoding protocol required by NSKeyedArchiver, so I don't see where would be your problem.
So, here are many ideas to test.
First, are you sure that the data you think you have are valid? In your first code snippet, you write [NSData dataWithContentsOfFile:#"0.png"]. This method expects an absolute file path.
Assuming the problem is not in your code, just in your question, let's continue:
Do you have something different than nil in the variable data after your archiving? Ie, after the assignement to data, can you add this code. If the assertion fail, you will get an exception at runtime:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
NSAssert(nil != data, #"My object data is nil after archiving");
If the problem was not here, what is the return of the line [data writeToFile:path options:NSDataWritingAtomic error:&error];
(Not the variable error, but the return value of the call to the method - writeToFile: options: error:)
What happens if you simplify your code and just do this:
result = [NSKeyedArchiver archiveRootObject:data
toFile:archivePath];
If everything was ok, have you tried to unarchive your file with NSKeyedUnarchiver?
The problem is that [NSData dataWithContentsOfFile:#"0.png"] looks for the file "0.png" in the current directory, but what the application thinks of as the current directory is probably not the place you're expecting. For graphical apps, you should always either use an absolute path or a path relative to some place that you can get the absolute path of (e.g. your app bundle, the application support directory, some user-selected location).
For command-line tools, using the current directory is more common. But I doubt that's the case here.
Another thing I noticed on Mavericks and up is that the folders in the path must be in existence. Meaning you must create the folder structure prior to saving into that folder. If you try to write to a folder on the desktop or elsewhere, even with sandboxing off, it will fail if the folder does not exist. I know this has been answered already, but I found that my issue continued regardless, but once I make sure that the folder structure was in place, I could do my writing to that folder.
On a side note: I'm sure that you could do this from NSFileManager, and I'll be doing that myself once I finalize my app structure, but hope this helps someone else lost in the sauce.