This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021.

Fans welfare: search # small program: iOS reverse, pay attention to the public number: iOS reverse welfare [digging gold booklet 50% discount code]

There is only one left, valid until 23:59 on November 30.

preface

Application scenario: Print commodity price labels and transaction receipts

Features: automatic connection to the recently used printer, unified processing bluetooth status

The problem solved: the problem of RMB ¥garbled characters

Effect drawing: Price tag printing (product name support multi-line display)

Note printing (automatic realization of % NS automatic filling space function)

Resources from CSDN download demo source: https://download.csdn.net/download/u011018979/14920529

private

Method to switch the printing mode of Jiabo printer: Press and hold down the FEED and Pause keys, and then open the start button to start up.

I. Obtain the label print command

- (NSData *)price_tscCommand{
    
    TscCommand *command = [[TscCommand alloc]init];
    [command addSize:40 :60];
    [command addGapWithM:2 withN:0];
    [command addReference:0 :0];
    [command addTear:@"ON"];
    [command addQueryPrinterStatus:ON];
    [command addCls];
    
    CGFloat marg = 10;
    CGFloat topY = 5;

    [command addTextwithX:200 withY:0+topY withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:@" Trade Name"];// The height of the word is 30
    / / spacing of 10
    / / 0, Barcode
    [command addTextwithX:30 withY:30+marg+topY withFont:@"TSS24.BF2" withRotation:0 withXscal:1 withYscal:1 withText:@ 2017.01.31 ""];
    [command add1DBarcode:30 :70 :@"CODE128" :100 :1 :0 :2 :2 :@"1kn23456984"];

    [command addTextwithX:47 withY:200+marg+topY withFont:@"TSS24.BF2"
             withRotation:0 withXscal:1 withYscal:1 withText:@ 6666.81 "/"];/ / selections
    / / 1, the selections
    UIImage *image = [CtrlViewController imageFromText:@ "selections" withFont:[UIFont systemFontOfSize:15] withColor:[UIColor blackColor]];

    
    [command addBitmapwithX:30 withY:200+marg withMode:0 withWidth:15 withImage:image];

    
    [command addPrint:1 :1];// M row n: column print two copies

    return [command getCommand];
}

Copy the code

1.1 Solve the problem of garbled characters of RMB ¥

/** convert text to UIImage for printing ¥to avoid garbled */+ (UIImage *)imageFromText:(NSString*)text withFont: (UIFont *)font withColor:(UIColor *)color
{

    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, MAXFLOAT)];
    CGRect rect = CGRectMake(0.0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(size,YES.0.0);
    NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByClipping;
    NSDictionary*attribute = @{NSFontAttributeName:font,
                               NSParagraphStyleAttributeName:paragraphStyle,
                               NSForegroundColorAttributeName:color
                               };
    // set the background color to B white because the font is black
    CGContextRef context = UIGraphicsGetCurrentContext(a);CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextFillRect(context, CGRectMake(0.0.200.200));
    //2, draw text into context
    [text drawWithRect:rect options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute context:nil];
    // get the image from the context
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(a);UIGraphicsEndImageContext(a);return image;
    
}

Copy the code

II. Obtain the ticket printing command

2.1 Store receipts: Use string formatting for typesetting

#pragmaMark-******** uses string formatting for ticket layout
+ (void) setupStoreListcommand:(EscCommand*)command name:(NSString*)name count:(char*)count price:(char*)price sum:(char*)sum {
    
// [count ]
    
    [command addSetJustification:0];
    
    
    [command addText:[NSString stringWithFormat:@"%@\n",name]];
    
    
    [command addSetJustification:2];
    
    /** %3s, format output string, right aligned, more than 3 lengths, all output; %7.2s, output string accounted for 7 positions, right align, left fill space, output 2 characters; %-5.3s: output 3 characters, occupy 5 positions, align left and fill space right. %.4s, output only 4 characters, placeholder 4 positions, right aligned; * /
    
    [command addText:[NSString stringWithFormat:@"%5s %8s %8s\n",count,price,sum]];
}
Copy the code

2.2 To avoid garbled characters, use %n@ instead of %ns for formatting

    NSString *text = [NSString stringWithFormat:@"%8@\t%8@\n",column1str,column2str];

Copy the code
  • Formatting not recommended
   NSString *text = [NSString stringWithFormat:@"%8s\t%8s\n",column1str.UTF8String,column2str.UTF8String];

Copy the code

2.3 Automatically realize the function of %ns automatically completing space

#pragmaMark-******** uses string formatting for ticket layout: 2 columns
+ (void) setupStoreListcommand:(EscCommand*)command column1Name:(NSString*)column1Name column1Value:(NSString*)column1Value  column2Name:(NSString*)column2Name column2Value:(NSString*)column2Value{
    

    NSString *column1str = [NSString stringWithFormat:@ % @ : % @ "",column1Name,column1Value];
    
    NSString *column2str = [NSString stringWithFormat:@ % @ : % @ "",column2Name,column2Value];
    
    
    
    
    [command addSetJustification:0];
    /** %3s, format output string, right aligned, more than 3 lengths, all output; %7.2s, output string accounted for 7 positions, right align, left fill space, output 2 characters; %-5.3s: output 3 characters, occupy 5 positions, align left and fill space right. %.4s, output only 4 characters, placeholder 4 positions, right aligned; * /
    // Char is unencoded and stores pure data
// kCFStringEncodingGBK_95
    //NSString stores UTF8 encoded data, %s outputs ASCII data, UTF8 encoded Chinese characters output in ASCII mode, must be garbled.
    
// char tmp = [column1str characterAtIndex:0];
    
    NSString *text = [NSString stringWithFormat:@"%8@\t%8@\n"[self addRightComplementspaces:column1str count:8], [self addRightComplementspaces:column2str count:8]].// NSString *text = [NSString stringWithFormat:@"%8s\t%8s\n",column1str.UTF8String,column2str.UTF8String];
/ / the String. Format (" % - 4 s % % % - 8 - s - 10 s - 4 s ", ""," 1243 kg ", "850000.00", "850000.00");
    [command addText:text];
}

// Create your own way of automatically completing Spaces

+ (NSString*)addComplementspaces:(NSString*)str count:(NSInteger)count{
    
    if (str.length>=count) {
        return str;
    }
    
    NSMutableString *tmp = [NSMutableString new];
    NSInteger tmpcount = count -str.length;
    for (int i =0; i< tmpcount; i++) {
        [tmp appendString:@" "];// Complete the space to the left
    }
    [tmp appendString:str];// Complete the space to the left
    return tmp;
}


// create your own way of automatically completing Spaces to the right

+ (NSString*)addRightComplementspaces:(NSString*)str count:(NSInteger)count{
    
    if (str.length>=count) {
        return str;
    }
    
    NSMutableString *tmp = [[NSMutableString alloc]initWithString:str];
    NSInteger tmpcount = count -str.length;
    for (int i =0; i< tmpcount; i++) {
        [tmp appendString:@" "];// Complete the space to the right
    }
    return tmp;
}

Copy the code

III. Realize automatic connection to the recently used printer

- (void)connectLastPrint{
    __weak __typeof__(self) weakSelf = self;

    [KNConnecterManagerTool listenBluetoothpoweredState:^(CBPeripheral * _Nullable peripheral) {
        
        
        return[weakSelf setupConnectPeripheral:peripheral]; }]; } - (void) setupConnectPeripheral:(CBPeripheral *_Nullable)peripheral{
    if ([peripheral.identifier.UUIDString isEqualToString:KBLUETOOTH]) {
        NSLog(@" If same, start to connect this Bluetooth");
        [Manager connectPeripheral:peripheral options:nil timeout:50 connectBlack:^(ConnectState state) {
            if (state == CONNECT_STATE_CONNECTED) {
                [Manager stopScan];
                // Change the status
                [self setupCONNECT_STATE_CONNECTED:peripheral];
                
            }else if (state == CONNECT_STATE_TIMEOUT || state == CONNECT_STATE_FAILT || state == CONNECT_STATE_DISCONNECT){
                
                if (state == CONNECT_STATE_DISCONNECT) {
                    [self setupCONNECT_STATE_DISCONNECT];
                    return ;
                }
                
                [SVProgressHUD showInfoWithStatus:Please try to restart the Bluetooth printer.];
                [selfconnectLastPrint]; }}]; }else{
        NSLog(@" Device not found"); }}/** * disconnect */
- (IBAction)disconnectAction:(id)sender {
    [Manager close];
}

#pragmaMark-******** Processing after successful connection to connectLastPrint

- (void) setupCONNECT_STATE_CONNECTED:(CBPeripheral*)peripheral{
    self.connState.text = [NSString stringWithFormat:@ % @ % @ "".@" Connection status: Connected",peripheral.name];
    [SVProgressHUD showInfoWithStatus:@" Connection successful"];
    // [SVProgressHUD show
    [self.navigationController popViewControllerAnimated:YES];
    
    //1. After the connection is successfully maintained
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setValue:peripheral.identifier.UUIDString forKey:@"blueTooth"];
    [user setValue:peripheral.name forKey:@"blueName"];
    [user synchronize];
}

Copy the code

The macro

#define kUserDefaults       [NSUserDefaults standardUserDefaults]
#define KBLUETOOTH         [kUserDefaults valueForKey:@"blueTooth"]// Merchant connected to print

Copy the code

IV. Frequently Asked Questions

4.1 Processing of iOS Bluetooth status [Processing of Bluetooth disabled and unauthorized]

  • Processing of iOS Bluetooth status [Processing of Bluetooth off and unauthorized]

4.2 CBCentralManagerStateUnsupported

If the timeout time is too long, this problem can be caused by changing it to a smaller time, such as 2.

        [Manager connectPeripheral:peripheral options:nil timeout:50 connectBlack:^(ConnectState state) {

Copy the code

V、 see also

More content please pay attention to # applets: iOS Reverse, only to present valuable information for you, focus on mobile technology research field; For more services and advice, please follow # publicid: iOS Reverse.