自动 AirPrint IOS

automatic AirPrint IOS

我需要在后台 Xcode 进行 AirPrint,无需用户交互。我不在乎是否必须使用第 3 方框架来执行此操作。这是我的代码,但需要用户的交互。

 NSMutableString *printBody = [NSMutableString stringWithFormat:@"%@",TextField.text];

    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    pic.delegate = self;


    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    printInfo.outputType = UIPrintInfoOutputGeneral;
    printInfo.jobName = @"PrintJob";
    pic.printInfo = printInfo;


    UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc] initWithText:printBody];
    textFormatter.startPage = 0;
    textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0);
    textFormatter.maximumContentWidth = 6 * 72.0;
    pic.printFormatter = textFormatter;
    pic.showsPageRange = YES;


void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
    if (!completed && error) {
        NSLog(@"Printing could not complete because of error: %@", error);
    }
};


    [pic presentAnimated:YES completionHandler:completionHandler];

如果有人能提供帮助那就太好了!

I found a video that helped a lot!这是 iOS 8 的 wwdc 视频,他们刚刚介绍了不使用 UIPrintInteractionController 进行打印的新方法。这里是。

    -(IBAction)print:(id)sender{

      NSMutableString *printBody = [NSMutableString stringWithFormat:@"Hey this is a test lets hope it works!"];

      UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
      pic.delegate = self;


      UIPrintInfo *printInfo = [UIPrintInfo printInfo];
      printInfo.outputType = UIPrintInfoOutputGeneral;
      printInfo.jobName = @"PrintJob";
      pic.printInfo = printInfo;


      UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc] initWithText:printBody];
      textFormatter.startPage = 0;
      textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0);
      textFormatter.maximumContentWidth = 6 * 72.0;
      pic.printFormatter = textFormatter;
      pic.showsPageRange = YES;
//save your printer using code also in video. 

      UIPrinter *SavedPrinterUserDefaults = [[NSUserDefaults standardUserDefaults]
                                             objectForKey:@"SavedPrinter"];
      [pic printToPrinter:SavedPrinterUserDefaults
        completionHandler:^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {
          if (completed && !error)
            NSLog(@"YAYA! it printed");
        }];

    }

希望对遇到同样问题的人有所帮助。 Here is more to read about what you can do with this new API!