美文网首页
附件下载并浏览

附件下载并浏览

作者: 雪域红鹰 | 来源:发表于2023-07-23 13:46 被阅读0次

1.附件下载

               NSMutableDictionary *parametersDic = [NSMutableDictionary new];
                parametersDic[@"id"] = @(dataModel.Id);
                [MBProgressHUD showActivityMessage:@""];
                   NSString *urlString = [NSString stringWithFormat:@"%@%@?id=%ld",API_MAIN_URL,API_Report_Download_URL,dataModel.Id];
                   NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:urlString parameters:nil error:nil];
                   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                   NSMutableDictionary * dicHeader = @{}.mutableCopy;
                
                   NSString *token = [User currentUser].token;
                   if ([Common isValidNSStringOBJ:token]) {
//                    dicHeader[@"Authorization"] = token;
                      [request setValue:token forHTTPHeaderField:@"Authorization"];
                   }
               
                  NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
                        NSLog(@"%lld   %lld",downloadProgress.completedUnitCount,downloadProgress.totalUnitCount);

                        NSLog(@"下载中....");
                    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

                        return [NSURL fileURLWithPath:[self getFilePath]];  //这里返回的是文件下载到哪里的路径 要注意的是必须是携带协议file://

                    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

                        
                        NSLog(@"下载完成");
                        if(error != NULL){
    
                        }else{
                            self.fileUrl = [filePath path];
                 
                        }
                    }];

                    [task resume];

2.获取下载文件地址


-(NSString *)getFilePath{
    //存储下载文件
 
    //文件 id /文件名称
    NSString * name = [NSString stringWithFormat:@"%@.docx",dataModel.name];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths lastObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //创建文件夹
    NSString * filesPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"files/%ld/",dataModel.Id]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filesPath]) {
        [fileManager removeItemAtPath:[filesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", name]] error:nil];
    }
    BOOL success =  [[NSFileManager defaultManager] createDirectoryAtPath:filesPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSLog(@"创建文件成功:%d", success);
    //创建文件
    NSString *filePath = [filesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", name]];
    
    int resule = [fileManager fileExistsAtPath:[filesPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", name]]];
    
    NSLog(@"文件路径:%@  %ld \n %@ ", filePath,resule,  [NSURL fileURLWithPath:filePath]);
    return filePath;
}

注意:下载文件已存在是删除再重新下载

##3. 文件预览 (WKWebView)

#import "WebViewController.h"
#import <WebKit/WebKit.h>


@interface WebViewController ()<WKUIDelegate,WKNavigationDelegate>


@property (nonatomic,strong) WKWebView *wkWebView;  //  WKWebView

@end
@implementation WebViewController

-(UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
    [self loadFileUrl];

}


#pragma mark lazy load
- (WKWebView *)wkWebView{
    if (!_wkWebView) {
  
        
        
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=100%,initial-scale=0.8,minimum-scale=0.25,maximum-scale=2,user-scalable=yes'); document.getElementsByTagName('head')[0].appendChild(meta);document.documentElement.style.webkitUserSelect='none';document.documentElement.style.webkitTouchCallout='none';";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = wkUController;

        
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
        _wkWebView.allowsBackForwardNavigationGestures = YES;
    // 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
     _wkWebView.allowsBackForwardNavigationGestures = YES;
    _wkWebView.UIDelegate = self;
     _wkWebView.navigationDelegate = self;

      
    }
    return _wkWebView;
}



#pragma mark private Methods
- (void)setupUI{
    self.view.backgroundColor = [UIColor whiteColor];
    
    //web
    WS(weakSelf)
    [self.view addSubview:self.wkWebView];
    [self.wkWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(weakSelf.view);
    }];
    
}

- (void)loadFileUrl {
    if (!self.urlString.length) {
        return;
    }
    NSURL *url = [NSURL fileURLWithPath:self.urlString];
    [_wkWebView loadFileURL:url allowingReadAccessToURL:url];
}

-(void)loadRequest{

    NSString *url = self.model.descUrl;
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
    [self.webview loadRequest:request];
 }

- (void)wkWebViewReload{
    [_wkWebView reload];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{

 }

  // 当内容开始返回时调用
  - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{

 }

 // 页面加载完成之后调用
 - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
     NSMutableString *str = [NSMutableString string];

//     [str appendString:@"var header = document.getElementsByTagName(\'header\')[0];"];
//     [str appendString:@"header.parentNode.removeChild(header);"];
//     [webView evaluateJavaScript:str completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//             NSLog(@"didFinishNavigation %@",result);
//     }];
 }

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
 }

 // 接收到服务器跳转请求之后调用
 - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{

 }

 // 在收到响应后,决定是否跳转
 - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
   NSLog(@"%@",navigationResponse.response.URL.absoluteString);
     //允许跳转

     decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
     //decisionHandler(WKNavigationResponsePolicyCancel);
 }

 // 在发送请求之前,决定是否跳转
 - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
     NSLog(@"%@",navigationAction.request.URL.absoluteString);
     //允许跳转
     decisionHandler(WKNavigationActionPolicyAllow);
     //不允许跳转
     //decisionHandler(WKNavigationActionPolicyCancel);
 }

相关文章

网友评论

      本文标题:附件下载并浏览

      本文链接:https://www.haomeiwen.com/subject/pbbfpdtx.html