附件下載并瀏覽

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]];  //這里返回的是文件下載到哪里的路徑 要注意的是必須是攜帶協(xié)議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{
    //存儲(chǔ)下載文件
 
    //文件 id /文件名稱
    NSString * name = [NSString stringWithFormat:@"%@.docx",dataModel.name];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths lastObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //創(chuàng)建文件夾
    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(@"創(chuàng)建文件成功:%d", success);
    //創(chuàng)建文件
    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. 文件預(yù)覽 (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;
    // 是否允許手勢左滑返回上一級(jí), 類似導(dǎo)航控制的左滑返回
     _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
// 頁面開始加載時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{

 }

  // 當(dāng)內(nèi)容開始返回時(shí)調(diào)用
  - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{

 }

 // 頁面加載完成之后調(diào)用
 - (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);
//     }];
 }

// 頁面加載失敗時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
 }

 // 接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用
 - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{

 }

 // 在收到響應(yīng)后,決定是否跳轉(zhuǎn)
 - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
   NSLog(@"%@",navigationResponse.response.URL.absoluteString);
     //允許跳轉(zhuǎn)

     decisionHandler(WKNavigationResponsePolicyAllow);
    //不允許跳轉(zhuǎn)
     //decisionHandler(WKNavigationResponsePolicyCancel);
 }

 // 在發(fā)送請(qǐng)求之前,決定是否跳轉(zhuǎn)
 - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
     NSLog(@"%@",navigationAction.request.URL.absoluteString);
     //允許跳轉(zhuǎn)
     decisionHandler(WKNavigationActionPolicyAllow);
     //不允許跳轉(zhuǎn)
     //decisionHandler(WKNavigationActionPolicyCancel);
 }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容