iOS 应用中加载文档pdf/word/txt

一、加载PDF文档:应用内打开文档、手机中其他应用打开文档 Demo

首先拖入一个文档pdf、word、txt,打开不同的文档知识 文件名字、类型修改即可

#import "ReadViewController.h"

@interface ReadViewController ()<UIDocumentInteractionControllerDelegate>
{
    UIDocumentInteractionController * readvc;
}
@end

@implementation ReadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self creatButton];
    
}


-(void)creatButton{
    
    NSArray * arrtext = @[@"在其他App中打开",@"AppPreView"];
    
    for (int i =0; i<2; i++) {
        
        UIButton * but = [UIButton buttonWithType:UIButtonTypeSystem];
        but.frame = CGRectMake(100, 100+i*80, 200, 60);
        but.tag = i;
        [but setTitle:arrtext[i] forState:UIControlStateNormal];
        
        [but addTarget:self action:@selector(but:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:but];
        
    }
    
    
}

-(void)but:(UIButton*)but{
    
    
    switch (but.tag) {
        case 0:
        {
            
            NSURL * urll = [[NSBundle mainBundle]URLForResource:@"CocoaChina" withExtension:@"pdf"];
            if (urll) {
                readvc = [UIDocumentInteractionController interactionControllerWithURL:urll];
                readvc.delegate = self;
                [readvc presentOpenInMenuFromRect:[but frame] inView:self.view animated:YES];
                
            }
            
        }
            break;
        case 1:{
            
            //yulan
            NSURL * urld =[[NSBundle mainBundle]URLForResource:@"CocoaChina"  withExtension:@"pdf"];
            
            if (urld) {
        
                readvc = [UIDocumentInteractionController interactionControllerWithURL:urld];
                readvc.delegate  = self;
                [readvc presentPreviewAnimated:YES];
                
                
            }
            
        }
        default:
            break;
    }
    
}

-(UIViewController*)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    
    return self;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
原文地址:https://www.cnblogs.com/xujiahui/p/7053304.html