iOS 无线打印功能(AirPrint)

本文介绍了一个简单的AirPrint打印实现方案,包括获取UIPrintInteractionController、设置打印信息、配置打印项及回调等步骤,并针对iPhone与iPad的不同展示方式进行了适配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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];

    }

}

因为我本身是做iPad端的,所以遇到了很多问题,例如:
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/

还有什么问题大家可以一起交流yuanpeng_victor@163.com


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值