Weex 實現檔案的下載

有稜角的圓發表於2017-08-04

需求:在使用weex框架時,我們使用vue檔案寫頁面,在native端載入伺服器端的js頁面時由於網路狀態的不確定性,我們需要在第一次載入的時候對js頁面進行本地儲存。也就是說我們需要把js檔案下載到本地,然後進行載入,這樣可以避免出現網路環境不好的情況下卡頓白屏等問題。

 


 

解決辦法:查了一些文件,發現直接在vue頁面內新增下載邏輯不太方便,所以使用的是原生端擴充套件的方法進行檔案的下載,關於原生端的擴充套件可以在這裡進行檢視http://weex-project.io/cn/references/advanced/extend-to-ios.html

 

邏輯:

注意:檔案路徑的規範,詳情參考上一篇部落格。

native端(ios)

原生類檔案:

.h

//  JSDownloaderModule.h
//  weidaikuan
//
//  Created by JianF.Sun on 17/7/31.
//  Copyright © 2017年 ever. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <WeexSDK/WeexSDK.h>

@interface JSDownloaderModule : NSObject

-(void)jydownloadJSFile:(NSString *)urlStr callback:(void(^)(NSString* path))callback;
    
@end

.m

//
//  JSDownloaderModule.m
//  weidaikuan
//
//  Created by JianF.Sun on 17/7/31.
//  Copyright © 2017年 ever. All rights reserved.
//

#import "JSDownloaderModule.h"
#import "AppDelegate.h"
#import "JYLoadingView.h"
#import "NSString+Utils.h"
@implementation JSDownloaderModule
    
WX_EXPORT_METHOD(@selector(jydownloadJSFile:callback:))
    //file:///var/mobile/Containers/Bundle/Application/{id}/WeexDemo.app/
    ///var/mobile/Containers/Data/Application/D99A000B-5E21-451C-B701-3350098EBFA3/Documents/infomation.js
-(void)jydownloadJSFile:(NSString *)urlStr callback:(void(^)(NSString* path))callback{
    JYLoadingView *loading = [JYLoadingView new];
    [loading jyShowLoadingview:@"正在載入"];
    NSLog(@"download----url----%@",urlStr);
    
    if ([urlStr hasPrefix:@"file:///"]) {//本地路徑直接返回
        [loading jyRemoveLoadingview:@"0"];
        callback(urlStr);
    }
    
    //http型別
    NSString *fileName = [self getFileName:urlStr];//待加密
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    
    NSString *dirpath = [NSString stringWithFormat:@"%@/JS",docDir];
    
    NSString *filepath = [NSString stringWithFormat:@"%@/%@",dirpath,fileName];
    
    if (![[NSFileManager defaultManager]fileExistsAtPath:dirpath]) {
        
        [[NSFileManager defaultManager] createDirectoryAtPath:dirpath withIntermediateDirectories:YES attributes:nil error:nil];
        
    }else{
        NSLog(@"有這個檔案了");
    }
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]) {
        NSString *pathNew = [NSString stringWithFormat:@"file://%@",filepath];
       
        dispatch_async(dispatch_get_main_queue(), ^{
            [loading jyRemoveLoadingview:@"0"];
            callback(pathNew);
        });
    }else{
    
    
    //1.網址
    NSURL *url=[NSURL URLWithString:urlStr];
    //2.請求
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    //3.佇列
    NSOperationQueue *queue=[[NSOperationQueue alloc]init];
    //4.傳送非同步請求
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * response, NSData *  data, NSError *  connectionError) {
    
        
        
        
        if (![data writeToFile:filepath atomically:YES]) {
            NSLog(@"檔案寫入錯誤");
            dispatch_async(dispatch_get_main_queue(), ^{
                [loading jyRemoveLoadingview:@"0"];
                
            });
        }else{
            
            NSString *pathNew = [NSString stringWithFormat:@"file://%@",filepath];

            dispatch_async(dispatch_get_main_queue(), ^{
                
                [loading jyRemoveLoadingview:@"0"];
                callback(pathNew);
            });
            
            
        }
     
     }];
    
    }
    
}
    //去掉http字首,獲取儲存檔案的名稱
-(NSString*)getFileName:(NSString*)urlStr{
    int length=(int)urlStr.length;
    // NSLog(@"length===%d",length);
    NSString *result=@"";
    for (int i=length-1; i>-1; i--) {
        if ([[urlStr substringWithRange:NSMakeRange(i, 1)] isEqualToString:@"/"]) {
            NSString *tem=[urlStr substringWithRange:NSMakeRange(i+1, length-i-1)];
            result=tem;
        
            return [result md5];
        }
    }
    return result;
}
    
    
@end

 

註冊自定義module:  

 [WXSDKEngine registerModule:@"jsdownloader" withClass:[JSDownloaderModule class]];


weex(js端)

獲取module
const jsdownloader = weex.requireModule('jsdownloader')

呼叫native埠


jsdownloader.jydownloadJSFile(config.jsURL('face.js'),function (e) {

                    console.log('callback'+e);

                    var url = e;
                    var params = {
                        'url': url,
                        'animated' : 'true',
                    }

                    navigator.push(params, function () {});
//                modal.toast({message: this.platform, duration:2})

                });

 大功告成!!!

 

 

相關文章