2012-05-18 48 views
-1

我需要將一系列打印機命令發送到Sato條形碼打印機。例如:如何使用打印機命令將NSString轉換爲NSData

<ESC>A 
<ESC>H0120 
<ESC>V0060 
<ESC>$B,180,180,0 
<ESC>$=Information 
... 

我有一個開放的TCP/IP連接到打印機,只是想寫一個NSData對象,如:

[connection write:data error:error]; 

wheras數據的NSData對象。我意識到我可以使用\ x1B中的二進制值將轉義符插入到字符串中。例如:

NSString *printString=[[NSString alloc]initWithString:@"\x1BA\X1BH0120\X1BV0060\X1B$B,180,180,0/X1B$=Information"]; 

我遇到的問題是我不知道如何將我的字符串轉換爲NSData進行寫入。

我欣賞任何建議。

回答

0

我會對我的一些發現進行更新,以防有人在將來遇到類似問題。我的問題是我需要將一系列打印機命令發送給Sato條碼打印機。佐藤使用專有語言,需要像上面的語法,而我需要發送像<ESC> A和<ESC> Z命令。我有一個開放的TCP/IP連接,並一直試圖發送幾個命令沒有運氣的方法。我雖然在我的翻譯NSData的問題。我很接近,但不夠近。問題原來是在我從一個文件轉換爲一個NSString ...不是當我將NSString轉換爲NSData時。嘗試使用\ x「轉義符」發送<ESC>的二進制等價物時,我也遇到了問題。我終於決定使用八進制等值。

// 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]; 

這裏是一些sato.txt文件的內容的樣本

\033A\033#E5\033Z 
\033A\033H0120\033V0060\033$B,180,180,0\033$=ItemID 

的\ 033是八進制轉義爲<ESC>

2

你可以簡單地做:

NSData *data = [printString dataUsingEncoding:NSUTF8StringEncoding];

選擇最適合您的需求,除了它的很簡單的編碼。

+0

請問NSUTF8StringEncoding保持二進制逃逸? – bridamax

+0

是的,它會的。這與編碼方面的常規英文文本沒有什麼不同。當你有特殊語言的特殊字符時要小心,如果你不使用合適的編碼,它們可能會顯示錯誤。 – Stefan

+0

好的。我早些時候嘗試過,並沒有得到預期的結果。我認爲逃逸序列沒有到達打印機,並在「翻譯」中丟失。它必須有更多與我與打印機的連接。我將不得不做更多關於如何連接到網絡打印機的研究。謝謝。 – bridamax