layabox Native 自己下载资源并缓存

我们在开发中,不管是打的网络版还是本地版,或多或少都有可能加载一些网络上的资源,并且这些资源不想用dcc方式,毕竟现在苹果对热更新管得比较严,那如果不用dcc方式,我们在Native上面的资源用Loader去加载后,并不会缓存到本地,这样会造成网络流量的浪费。

经过我对Laya生成的Native中的js脚本进行分析,以及多次尝试才做出来,而官方很不想帮忙回答这些问题,一问问题就是让你交钱成VIP。

下面是我的代码:

private function downloadFile(url:String,relativePath:String,onComplete:Handler,onError:Handler=null):void{
		
	if(window.conch)
	{
		var folder:String=window.conch.getCachePath()+"/";
		var relativeFolder:String = folder+relativePath.substring(0,relativePath.lastIndexOf("/"));
		if (!window.fs_exists(relativeFolder)) {
			window.fs_mkdir(relativeFolder);
		}

		var cachepath:String = folder+relativePath;
		//判断文件是否存在
		if (window.fs_exists(cachepath)) {
			onComplete && onComplete.runWith("file://"+cachepath.replace(new RegExp('//','g'),"/"));
			return;
		}
	
		var f:* = new window.conch_File(url);
			var fr:* = new window.conch_FileReader();
		fr.setIgnoreError(true);
		fr.onload = function():void {
    		if(fr.result){
				window.fs_writeFileSync(cachepath, fr.result);
				onComplete && onComplete.runWith("file://"+cachepath.replace(new RegExp('//','g'),"/"));
			}
			else
			{
				onError && onError.runWith("no data");
			}
		};
		// fr.onprogress = onprog;
		fr.onerror = function(e):void{ 
			onError && onError.runWith(e);
		};
		fr.readAsArrayBuffer(f);
	}
	else
	{
		onComplete && onComplete.runWith(url);
	}
}

 

使用的代码:

var url:String="https://xxxxxxxx.xxx.xxx/2_3/2_3.png";
downloadFile(url,"2_3/2_3.png",Handler.create(this,function(localPath:String):void{
	Laya.loader.load(localPath,Handler.create(this,function(t:Texture):void{

		url="https://xxxxxxxx.xxx.xxx/2_3/2_3.sk";
		downloadFile(url,"2_3/2_3.sk",Handler.create(this,function(localPath:String):void{
			
			var ske:Skeleton = new Skeleton();
			ske.url=localPath;
			ske.pos(300,300);
			Laya.stage.addChild(ske);

		}));

	}));
}));

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值