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