Search code examples
objective-cxcodecocoaprintingpdfdocument

Getting 'unrecognized selector sent to instance' with PDFDocument initWithData?


I'm using jsPDF in a webview to generate a PDF that I'd like to print out on a connected USB label printer. I'm getting a 'unrecognized selector sent to instance' error.

Here is the error from the Xcode console:

-[__NSCFString bytes]: unrecognized selector sent to instance 0x1089cb868

Here is the function for reference:

- (void) printPDFwithPrinter: (NSString *) printerName andData: (NSData *) data{

    NSLog(@"%@", printerName);

    PDFDocument *pdfDocument = [[PDFDocument alloc] initWithData:data];

    NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
    [printInfo setTopMargin:0.0];
    [printInfo setBottomMargin:0.0];
    [printInfo setLeftMargin:0.0];
    [printInfo setRightMargin:0.0];
    [printInfo setHorizontalPagination:NSFitPagination];
    [printInfo setVerticalPagination:NSFitPagination];
    [printInfo setPrinter:[NSPrinter printerWithName:printerName]];

    PDFPrintScalingMode scale = kPDFPrintPageScaleDownToFit;

    NSPrintOperation *op = [pdfDocument printOperationForPrintInfo: printInfo scalingMode: scale autoRotate: YES];

    [op setShowsPrintPanel:NO];
    [op setShowsProgressPanel:NO];
    [op runOperation];
}

The pdf data is the raw output of the pdf body as a string. (Docs)

I'm brand new to Objective-C, so I'm using AppBurger for my Native/webview bridge (building my app in HTML/JS/CSS).

Here is my Xcode project so far: https://github.com/josiaho/AppBurger-Print-Test


Solution

  • How to debug:

    1. Add a breakpoint on the line PDFDocument *pdfDocument = [[PDFDocument alloc] initWithData:data];

    2. Test the app. When the app hits the breakpoint, inspect data.

    3. data is a NSString and initWithData: expects NSData.

    How to fix:

    1. Rename

    - (void) printPDFwithPrinter: (NSString *) printerName andData: (NSData *) data

    to

    - (void) printPDFwithPrinter: (NSString *) printerName andString: (NSString *) string

    1. Convert string to NSData.

    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

    1. Test the app.