注意:
1.UIDocumentInteractionController
需要聲明成屬性,避免過早釋放
2.本地文件的路徑使用[NSURL fileURLWithPath:filePath]
視圖控制器層
@interface GKAttachmentPreviewController ()<UIWebViewDelegate,UIDocumentInteractionControllerDelegate>
@property (strong, nonatomic)UIWebView *webView;
/**
系統擴展(必須寫成屬性,避免過早釋放引起的崩潰)
*/
@property (strong, nonatomic)UIDocumentInteractionController *documentController;
/**
本地附件地址
*/
@property (copy, nonatomic)NSURL *localAttachmentUrl;
@end
@implementation GKAttachmentPreviewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = kWhiteColor;
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"systemShare"] style:UIBarButtonItemStylePlain target:self action:@selector(openSystemShare)];
self.navigationItem.rightBarButtonItem.enabled = NO;
/// 下載附件
[self downAttachment];
}
#pragma mark - 打開系統分享
- (void)openSystemShare{
if (!self.localAttachmentUrl) {
return ;
}
if (!self.documentController) {
self.documentController = [UIDocumentInteractionController interactionControllerWithURL:self.localAttachmentUrl];
}
self.documentController.URL = self.localAttachmentUrl;
/// 打開系統擴展頁面
[self.documentController presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];
}
#pragma mark - 下載附件
- (void)downAttachment{
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
hud.labelText = @"下載附件中";
__weak __typeof(self) weakSelf = self;
[GKAttachmentMG downAttachmentWithUrl:self.attachmentUrlStr progress:^(NSProgress *progress) {
dispatch_async(dispatch_get_main_queue(), ^{
hud.progress = progress.fractionCompleted;
});
} success:^(id result) {
weakSelf.navigationItem.rightBarButtonItem.enabled = YES;
#warning 文件路徑使用[NSURL fileURLWithPath:path]
weakSelf.localAttachmentUrl = [NSURL fileURLWithPath:[result absoluteString]];
dispatch_async(dispatch_get_main_queue(), ^{
[hud hide:YES];
if ([GKAttachmentMG attachmentCanOpenOnWebView:[result absoluteString]]) {
[weakSelf.webView loadRequest:[NSURLRequest requestWithURL:result]];
}else{
[weakSelf openSystemShare];
}
});
} fail:^(id error) {
dispatch_async(dispatch_get_main_queue(), ^{
[hud hide:YES];
});
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"附件下載出錯,請稍后重試" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
[alertController addAction:[UIAlertAction actionWithTitle:@"重試" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
[weakSelf downAttachment];
}]];
[weakSelf.navigationController presentViewController:alertController animated:YES completion:nil];
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - lazyload
- (UIWebView *)webView{
if (!_webView) {
_webView = [[UIWebView alloc]init];
_webView.delegate = self;
_webView.multipleTouchEnabled = YES;
_webView.scalesPageToFit = YES;
[self.view addSubview:_webView];
[_webView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.view);
}];
}
return _webView;
}
附件文件下載緩存管理
#pragma mark - 判斷附件是否可用瀏覽器打開
- (BOOL)attachmentCanOpenOnWebView:(NSString *)fileUrl{
// 附件文件類型
NSString *fileType = [fileUrl pathExtension];
NSArray *imgTypes = @[@"png",@"jpg",@"jpeg",@"gif"];
NSArray *officeTypes = @[@"doc",@"docx",@"ppt",@"pptx",@"xls",@"xlsx",@"pdf",@"txt"];
if ([imgTypes containsObject:fileType]) {
// 圖片文件類型
return YES;
}else if([officeTypes containsObject:fileType]){
// 辦公文件類型
return YES;
}else{
// 未知文件類型
return NO;
}
}
#pragma mark - 下載附件
- (void)downAttachmentWithUrl:(NSString *)url progress:(ProgressBlock)progress success:(SuccessBlock)success fail:(FailBlock)fail{
NSURL *cacheFileUrl = [self checkCacheFileWithFileUrl:url];
if (cacheFileUrl) {
success(cacheFileUrl);
}else{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 獲得網絡管理者
AFURLSessionManager *manager = [[AFURLSessionManager alloc]initWithSessionConfiguration:configuration];
// 創建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
progress(downloadProgress);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
// 告訴服務器下載的文本保存的位置在那里
NSString *path = [NSString stringWithFormat:@"%@/%@/attachments/%@",kDocumentPath,[EnvironmentVariable getUserID],response.suggestedFilename];
return [NSURL fileURLWithPath:path];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if (error) {
fail(error);
}else{
success(filePath);
}
}];
[downloadTask resume];
}
}
#pragma mark 檢查附件本地緩存
- (NSURL *)checkCacheFileWithFileUrl:(NSString *)fileUrl{
NSString *fileName = [fileUrl lastPathComponent];
// 本地文件路徑
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fileFolderPath = [NSString stringWithFormat:@"%@/%@/attachments",kDocumentPath,[EnvironmentVariable getUserID]];
// 如果存在附件緩存文件夾,則創建
if (![fileManager fileExistsAtPath:fileFolderPath]) {
[fileManager createDirectoryAtPath:fileFolderPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *filePath = [fileFolderPath stringByAppendingPathComponent:fileName];
/* 判斷是否有緩存文件 */
if ([fileManager fileExistsAtPath:filePath]) {
return [NSURL URLWithString:filePath];
}else{
return nil;
}
}