How can I convert an NSString with printer commands into NSData - objective-c

I need to send a series of printer commands to a Sato barcode printer. For example:
<ESC>A
<ESC>H0120
<ESC>V0060
<ESC>$B,180,180,0
<ESC>$=Information
...
I have an open tcp/ip connection to the printer and simply want to write an NSData object, such as:
[connection write:data error:error];
wheras data is an NSData object. I realize that I can insert the escape into a string using the binary value with \x1B. For example:
NSString *printString=[[NSString alloc]initWithString:#"\x1BA\X1BH0120\X1BV0060\X1B$B,180,180,0/X1B$=Information"];
The problem I'm having is that I don't know how to translate my string to NSData for the write.
I appreciate any suggestions.

You can simply do:
NSData *data = [printString dataUsingEncoding:NSUTF8StringEncoding];
Choose the encoding that best suits your needs, apart from that it's pretty straightforward.

I'll give an update on some of my findings in case someone stumbles upon a similar problem in the future. My problem was that I needed to send a series of printer commands to a Sato barcode printer. Sato uses a proprietary language that requires syntax like above whereas I needed to send commands like <ESC>A and <ESC>Z. I had an open tcp/ip connection and kept trying several methods to send the commands with no luck. I though the problem was in my translation to NSData. I was close, but not close enough. The problem turned out to be in my translation from a file to an NSString...not when I was converting the NSString to NSData. I also had problems trying to use \x "escapes" to send the binary equivalent of <ESC>. I finally settled on using the octal equivalent.
// load the appropriate file as a string
NSString *filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"sato.txt"];
NSError *firstError=nil;
NSString *satoData=[[NSString alloc]initWithContentsOfFile:filePath encoding:NSNonLossyASCIIStringEncoding error:&firstError]; // the NSNonLossyASCIIStringEncoding was the key to correcting my problem here.
satoData=[satoData stringByReplacingOccurrencesOfString:#"Description" withString:self.description];
satoData=[satoData stringByReplacingOccurrencesOfString:#"ItemID" withString:self.itemId];
satoData=[satoData stringByReplacingOccurrencesOfString:#"Quantity" withString:self.printQty];
NSDate *now=[NSDate date];
NSString *formattedDate=[NSDateFormatter localizedStringFromDate:now dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
satoData=[satoData stringByReplacingOccurrencesOfString:#"Date" withString:formattedDate];
NSData *data=[satoData dataUsingEncoding:NSUTF8StringEncoding];
[connection write:data error:error];
Here is a sample of some of the contents of the sato.txt file
\033A\033#E5\033Z
\033A\033H0120\033V0060\033$B,180,180,0\033$=ItemID
The \033 is the octal escapes for <ESC>

Related

How to NSLog NSData JSON response in JSON format?

Is there a way I can NSLog JSON response of NSData in JSONformat?
NSLog(#"JSON NSString: %#" ,jsonData);
In this post they are printing NSDictionary,I can convert it to NSDictionary. and this solution returns (null).
How can I NSLog in JSON format?
• What's wrong:
jsonData (as you gave) IS NOT a hexData representing a JSON.
• Quick hack (not viable solution!) to get your JSON to use in your site CodeBeautify:
NSDictionary *dictFromData = [NSKeyedUnarchiver unarchiveObjectWithData:jsonData];
NSData *realJSONData = [NSJSONSerialization dataWithJSONObject:dictFromData options:0 error:nil];
NSString *strFINAL = [[NSString alloc] initWithData:realJSONData encoding:NSUTF8StringEncoding];
NSLog(#"StrFINAL: %#", strFINAL);
Note: Yeah, I bypassed the error parameters, and we shouldn't. With
NSJSONWritingPrettyPrinted instead of 0 in options: parameter, you have a result almost similar to the one of CodeBeautify.
• How did I get there:
Firt, I copy/paste your bump string of NSData with this answer.
That way, I got jsonData as you got.
Then, I tried simply what it should be given your informations:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&errorJSON];
Which didn't work giving the error:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be
completed. (Cocoa error 3840.)" (Invalid value around character 0.)
UserInfo=0x17598540 {NSDebugDescription=Invalid value around character
0.}
But with NSDictionary *dictWithData = [NSKeyedUnarchiver unarchiveObjectWithData:jsonData];, I managed to get the real NSDictionary. But NSKeyedArchiver/NSKeyedUnarchiver are doing something "equivalent" to NSJSONSerialization: it serializes, transforming a NSObject into NSData (and vice-versa). But more powerful: for any kind of object that are NSCoding compliant. Here, since it's originally from a JSON (only NSString, NSNumber, NSArray and NSDictionary objects, and not a custom one), it's working without any more code.
Did you for instance tried to save it into NSUserDefaults and it's not a .plist either (that was also one on my tries, I saved jsonData into memory, and used dictionaryWithContentsOfFile: giving me weird answer, but a important one in the bump of it: ""$class" = "{value = 23}";" which lead me to NSKeyArchiver/NSKeyUnarchiver). I don't know what you did exactly.
• Conclusion:
So clearly, somewhere, you mixed stuff found on the web. You need to rework that. You can't let it like this. There is issue in your code elsewhere. Where did you get jsonData from? What did you do with it?
Code:
NSLog("Formatted JSON : %#" ,[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
There are different situations. If parsing the JSON data was fine, then you just want to log the result (dictionary or array). If parsing the JSON data failed, and you suspect there is something wrong with the JSON data, then you convert the JSON data to an NSString and log that. And finally, if either conversion to NSString failed, or you look at the NSString and can't find what's wrong with it, then you log the NSData itself to be able to see the bytes. That's useful if someone managed to put control characters or some other nonsense into your JSON data.
The best is to write a method (warning! not for the timid! requires writing code yourself) that takes the NSData, analyses it and prints out the information that you need.

NSString value as NSData output

I have a NSString which is #"15".
I want my NSData to be 15 also. I know how to convert it to get the value 31 35 but I would like my NSData to be 15 if I use NSLog on it. I'm not asking for a conversion but more for a translation. I don't wanna change the NSLog print but the NSData value. Is there anyway to do it ?
Parse the string to an integer (lets assume a signed 32-bit integer):
NSString *str = #"15";
int32_t i = (int32_t)[str intValue];
To encode it in native endian:
NSData *data = [NSData dataWithBytes:&i length:sizeof(i)];
Note: if you intend to transmit that data to another computer then you need to decide on a common endianness of primitive types. Big endian is traditionally used and facilitated with functions like htonl(), ntohl(), etc. If the computers are all the same platform then you can use the native endianness, for a slight performance boost and code simplification.
You need to convert the string to a byte first (by parsing it). Then you can build the NSData from the byte.

Storing and retrieving NSAttributedString

I want to store my Rich Text for UITextView's NSAttributedString. For this as suggested in a question on stackoverflow, I choose NSData. Problem is app crashes while un-archiving and retrieved data is also not same as the saved NSData.
Explanation
DB:
Saving Data into DB
In DB I have a column named rtfText with datatype blob -> (rtfText blob)
While Saving into DB, I do this
NSData *data = [NSKeyedArchiver archiveWithRootObject:_myTextView.attributedString];
and sends the data like this in query
NSString Query = [NSString stringWithFormat:#"Insert into table (rtfText) VALUES \"%#\")",data];
Retrieving Data From DB
Data is retrieved like this:
NSData *data = [[NSData alloc] initWithBytes:(sqlite3_column_blob(statement, 18)) length:sqlite3_column_bytes(statement, 18)];
UnArchive:
From the retrieved NSData from DB I unarchive it into NSAttributedString like this
_myTextView.attributedText = [NSKeyedUnarchiver unarchiveObjectWithData:data]; **<- App Crashes at this point giving error**
Error:
-[__NSCFData objectForKey:]: unrecognized selector sent to instance 0x15d56e80
I even tried to save NSAttributedString to NSData after Archive then converting it to NSString using NSASCIIStringEncoding but DB crashes then. I also tried saving it like this. First using NSKeyedArchiver converted NSAttributedString to NSData then to NSString using NSUTF8StringEncoding which gave me null string.
Kindly look into this.
Thanks in advance
Data Never inserted properly into database. Reason is Query on sqlite3 is always in the form of UTF8. NSString has to be converted to UTF-8 to make a query. After this conversion stored NSData in database is totally changed i.e. encoded again via UTF-8.
When I retrieved the data, it was not same as the old one. Therefore got error while un archiving it.
Solution: Stored NSData into sqlite3 without converting to UTF-8 and used sqlite_bind_blob for storing blob data to sqlite3 database.

Removing unicode and backslash escapes from NSString converted from NSData

I am converting the response data from a web request to an NSString in the following manner:
NSData *data = self.responseData;
if (!data) {
return nil;
}
NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)[self.response textEncodingName]));
NSString *responseString = [[NSString alloc] initWithData:data encoding:encoding];
However the resulting string looks like this:
"birthday":"04\/01\/1990",
"email":"some.address\u0040some.domain.com"
What I would like is
"birthday":"04/01/1990",
"email":"some.address#some.domain.com"
without the backslash escapes and unicode. What is the cleanest way to do this?
The response seems to be JSON-encoded. So simply decode the response string using a JSON library (SBJson, JsonKit etc.) to get the correct form.
You can replace (or remove) characters using NSString's stringByReplacingCharactersInRange:withString: or stringByReplacingOccurrencesOfString:withString:.
To remove (convert) unicode characters, use dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES (from this answer).
I'm sorry if the following has nothing to do with your case: Personally, I would ask myself where did that back-slashes come from in the first place. For example, for JSON, I'd know that some sort of JSON serializer on the other side escapes some characters (so the slashes are really there, in the response, and that is not a some weird bug in Cocoa). That way I'd able to tell for sure which characters I have to handle and how. Or maybe I'd use some kind of library to do that for me.

NSString writeToFile with URL encoded string

I have a Mac application that keeps it's own log file. It appends info to the file using NSString's writeToFile method. One of the things that it logs are URL's of web services that it is interacting with. To encode the URL, I'm doing this:
searchString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)searchString, NULL, (CFStringRef)#"!*'();:#&=+$,/?%#[]", kCFStringEncodingUTF8 );
The app then appends searchString to the rest of the URL and writes it to the log file. Now the problem is that after adding that URL encoding line, nothing seems to be getting written to the file. The program functions as expected otherwise however. Removing the line of code above results in all of the correct information being logged to the file (removing that line is not an option because searchString must be URL encoded).
Oh and I am using NSUTF8StringEncoding when writing the NSString to the file.
Thanks for any help.
EDIT: I know there's also a similar function to CFURLCreateStringByAddingPercentEscapes in NSString, but I've read that it doesn't always work. Can anyone shed some light on this if my original question cannot be answered? Thanks! (EDIT: same problem occurs when using stringByAddingPercentEscapesUsingEncoding:)
EDIT 2: Here's the code that I'm using to append messages to the log file.
+(void)logText:(NSString *)theString{
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:#"Folder/File.log"];
NSString *fileContents = [[[NSString alloc] initWithContentsOfFile:path] autorelease];
if([fileContents lengthOfBytesUsingEncoding:NSUTF8StringEncoding] >= 204800){
fileContents = #"";
}
NSString *timeStamp = [[NSDate date] description];
timeStamp = [timeStamp stringByAppendingString:#": "];
timeStamp = [timeStamp stringByAppendingString:theString];
fileContents = [fileContents stringByAppendingString:timeStamp];
fileContents = [fileContents stringByAppendingString:#"\n"];
[fileContents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
}
Because after almost a whole day no one else has offered any answers, I'm going to post a wild guess here: you're not accidentally using the string you want to output (with percent characters in it) as a format string are you?
That is, making the mistake of doing:
NSLog(#"In format strings you can use %# as a placeholder for an object, and %i for a plain C integer.")
Instead of:
NSLog(#"%#", #"In format strings you can use %# as a placeholder for an object, and %i for a plain C integer.");
But I'm going to be surprised if this turns out to be the cause of your problem, as it usually causes random-looking output, rather than absolutely no output. And in some cases, Xcode also gives compiler warnings about it (when I tried NSLog(myString), I got "warning: format not a string literal and no format arguments").
So don't shoot me down if this answer doesn't help. It would be easier to answer your question if you could show us more of your logging code. As for the one line you provided, I can't detect anything wrong with it.
Edit: Oops, I kind of missed that you mentioned you're using writeToFile:atomically:encoding:error: to write the string to the file, so it's even more unlikely you're accidentally treating it as a format string somewhere. But I'm going to leave this answer up for now. Again, you should really show us more of your code though ...
Edit: Regarding your question on a method in NSString that has similar percent encoding functionality, that would be stringByAddingPercentEscapesUsingEncoding:. I'm not sure what kind of problems you're thinking of when you say you've heard it doesn't always work. But one thing is that CFURLCreateStringByAddingPercentEscapes allows you to specify extra characters that don't normally have to be escaped but which you still want to be escaped, while the method of NSString doesn't allow you to specify this.