1.获取UIPrintInteractionController
2.设置Print Info
3.设置printingItem
4.设置打印回调
5.弹出UIPrintInteractionController
AirPrint打印简单实现主要代码:
-(void)printDocument
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"CSL_Icon" ofType:@"jpg"];
if (path == nil)
{
[self showAlertView:@"No Data" withMessage:nil];
return;
}
NSData *myData = [NSData dataWithContentsOfFile: path];
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
if(pic && [UIPrintInteractionController canPrintData: myData] ) {
pic.delegate = self;
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = [path lastPathComponent];
printInfo.duplex = UIPrintInfoDuplexLongEdge;
pic.printInfo = printInfo;
pic.showsPageRange = YES;
pic.printingItem = myData;
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) = ^(UIPrintInteractionController *pic, BOOL completed, NSError *error) {
//self.content = nil;
if (completed)
{
[self showAlertView:@"Success" withMessage:nil];
}
else if (!completed && error)
{
[self showAlertView:@"Faile" withMessage:@"Please, try agian!"];
// NSLog(@"FAILED! due to error in domain %@ with error code %u", error.domain, error.code);
}
};
[pic presentAnimated:YES completionHandler:completionHandler];
}
}
presentAnimated(:completionHandler:)
方法是在 iPhone 上呈现打印
UI。如果是从 iPad 打印,使用 presentFromBarButtonItem(:animated:completionHandler:)
或presentFromRect(:inView:animated:completionHandler:)
方法代替。if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
[printController presentAnimated:YES completionHandler:completionHandler];
// iPhone使用这个方法
}
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
[printController presentFromRect:showRect inView:viewController.view animated:YES completionHandler:completionHandler];
// iPad使用这个方法
}
苹果官方文档:https://developer.apple.com/airprint/