Giter Site home page Giter Site logo

mlzxy / ionic-cache-src Goto Github PK

View Code? Open in Web Editor NEW
138.0 11.0 55.0 10.01 MB

A Ionic Plugin for caching, works for any tags, and will show a progress circle when the download is not done

Home Page: http://market.ionic.io/plugins/ionic-cache-src

License: MIT License

JavaScript 97.39% TypeScript 2.61%

ionic-cache-src's Introduction

NOTICE

I will try to spare my time to work on a ionic2 version in typescript.

in the 0.7.2

  • Add encode option for URI
  • Roll back watch to observe
  • Find java.io.EOFException issue for old android causing the fileTransfer failed, if so don't cache.

in the 0.7.0

ionic-cache-src

Just change src to cache-src

    <img alt="" cache-src="http://a1.att.hudong.com/03/23/01300000332400125809239727476.jpg"/>

and it will take the rest work for you.

Demo

simple

complex

Install

  • bower
bower install ionic-cache-src
<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
<script src="cordova.js"></script>
<script src="cordova_plugins.js"></script> <!-- This one is optional -->
<script src="lib/ngstorage/ngStorage.min.js"></script>
<script src="lib/angular-svg-round-progressbar/build/roundProgress.min.js"></script>
<script src="lib/ionic-cache-src/ionic-cache-src.js"></script>
cordova plugin add cordova-plugin-file cordova-plugin-file-transfer
  • add ionic-cache-src to your angular module declaration dependencies
angular.module('myApp', ['ionic','ionic-cache-src'])
  • Done

How it Work

very simple strategy



Usage

Custom the progress circle

it accepts all options for angular-svg-round-progressbar , except for current

Change src

<img cache-src="" src-is="alt" />

will be rendered to

<img alt="file://xxx/xx/xxx.jpg" />

not so useful though.

Background image

<div  cache-src="http://farm4.static.flickr.com/3131/2877192571_3eb8bcf431.jpg"
src-is="background" >
<!-- stuff -->
</div>

Video

<video id="video" width="400"  controls  cache-src="http://vjs.zencdn.net/v/oceans.png" src-is="poster">
    <source cache-src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
        Your browser does not support HTML5 video.
</video>

Expire

<img alt="" cache-src="http://a1.att.hudong.com/03/23/01300000332400125809239727476.jpg" expire="{{60}}"/>

Set expiration time to 60 seconds. At the next page load and directive linking, this cache will be renewed if 60s passed. But there wouldn't be progress circle, the image will be replaced after the newly downloaded file is ready.

The expiration time is Infinity by default.

EncodeURI

    <img alt="" cache-src="http://a1.att.hudong.com/03/23/01300000332400125809239727476.jpg" encode-uri="false"/>

CordovaFileTransfer encodes URL by default, but some urls don't need. See this issue #17

Custom background style

<div  cache-src="http://farm4.static.flickr.com/3131/2877192571_3eb8bcf431.jpg"
src-is="background"
background-style="no-repeat center"
background-loading-style="url('path/to/your/loading/image.gif') no-repeat center"
>
<!-- stuff -->
</div>
  • background-style will be used as
<div style="background:url('image/url') {{backgroundStyle}}">
<!-- stuff -->
</div>
  • Default background-loading-style is url('lib/ionic-cache-src/img/loader.gif') no-repeat center

Inline progress circle

By default the progress circle is a block div, here is source code.

function makeProgressCircle($scope, $compile) {
    return angular.element($compile('<div style="{{circleContainerStyle}}"><div round-progress  max="max"  current="progress"  color="{{color}}" bgcolor="{{bgcolor}}"  radius="{{radius}}"  stroke="{{stroke}}"  rounded="rounded" clockwise="clockwise" iterations="{{iterations}}"  animation="{{animation}}"></div></div>')($scope));
};

So you could change its style using circleContainerStyle

<div class="list">
    <a class="item item-avatar" href="#">
        <img cache-src="http://x1.zhuti.com/down/2012/12/13-win7/llx-1.jpg"
            circle-container-style="display:inline-block;position:absolute;left:30px;"/>
        <h2>inline progress circle</h2>
        <p>Test Progress Circle as inline block</p>
    </a>
</div>

Callback

<img cache-src="" on-error="onError" on-start="onStart" on-finish="onFinish" on-progress="fun" />
function onError(err){}
function onStart(originUrl){}
function onFinish(naiveUrl){}
function onProgress(number){}

Note that the OnProgress and OnStart will only be called if a download is needed.

Work in broswer

It will works in browser with a mock download process.

For local file path

The plugin will download and cache the file if the url is http, https or ftp, otherwise it won't.

So it works for local file path, or base64 etc...

Service

This plugin store cache info as $localstorage.cache_src = {RemoteUrl:LocalUrl}, and there is a factory you could used to access the cache:

module.controller('Ctrl', function(cacheSrcStorage) {
    cacheSrcStorage.get('url') // === the local cache path for 'url'
});

which you can use to access the cached file

Config

module.config(function($cacheSrcProvider){
    $cacheSrcProvider
              .set('key',value)
              .set({key:value}); // set option
})

Key, Value for options like

  • srcIs

  • onError for global use etc...

  • showProgressCircleInBrowser whether show progress circle in browser

  • showProgressCircleInDevice whether show progress circle in device

  • interval browser mock progress circle period, by default 200.

  • options for progress circle angular-svg-round-progressbar

  • backgroundStyle and backgroundLoadingStyle

  • circleContainerStyle

  • expire

  • Anything you like, if you use custom progress indicator.

Note that the in-tag config has the higher priority than $cacheSrcProvider

Use custom progress indicator instead of built-in progress circle

Use callback

uiOnStart, uiOnProgress, uiOnFinish

You could take reference of the default source of this three functions, which implements the progress circle, and write your custom progress indicator.

To use your own uiOn* functions

module.config(function($cacheSrcProvider){
    $cacheSrcProvider
              .set('uiOnStart', myUiOnStart)
              .set('uiOnProgress', myUiOnProgress)
              .set('uiOnFinish', myUiOnFinish);
}); 



Attention

cordova_plugins.js

Because of ionic-team/ionic-plugin-keyboard#82 , the ionicPlatform.ready may fail from exception. If you encounter this problem, Add

<script src="cordova_plugins.js"></script>

solve it.

android:cordova-plugin-file

For android, you may need to add this

<preference name="AndroidPersistentFileLocation" value="Internal" />

to your config.xml, as mentioned in #10. Otherwise the image won't be loaded, and no error console.log.

livereload

When using live reload, you’re actually running the assets off the computer and not the device

You will get an error: Not allowed to load local resource, but it will only occur when livereloading.

iOS 9 NSAppTransportSecurity

Because iOS 9 forbids arbitrary http request, you may add

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key><true/>
</dict>

to you .plist file. Details in this gist: https://gist.github.com/mlynch/284699d676fe9ed0abfa

ionic-cache-src's People

Contributors

candidodmv avatar movibe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ionic-cache-src's Issues

WKWebView support

Has anybody managed to make this plugin work with wkwebview with local server?

Not working with ng-repeat on a device

I tested it with multiple images using ng-repeat and it works in browser, but not on a device (Tested on iPhone, iOS9), but it works with collection-repeat on a device.

Tested on latest Ionic version 1.2.4

(iOS) Videos don't load/play after 16 videos have been played

After 16 cashed videos are played (Same video or different) the plugin stops playing all loaded videos, closing the app and opening it again then fixes it until that 'video play' limit is reached again.

From my tests it consistently stops working after playing 16 cached videos in a row.
All videos do work if they are within the first 16 played.

It doesn't appear to make a difference if the videos are loaded from different URLs of the same URL.

This behaviour can be observed on the ionic-cashed-src-demo by repeating (in the view code) the videos in the video tab.

`


`

This behavior has been observed on:

  • iPad Air 1 running iOS 10.0.2 => couldn't play the 17th video
  • iPhone 6 Running iOS 9.3.5 => couldn't play the 17th video

The behaviour was not observed on:

  • Samsung Tab A (SM-350) Running android 6.0 => no issue

how to use this with ionic 2

Hi @benbbear ,
I really appreciate for this, it's a very nice library.
I am working on ionic 2, wanted to implement this in ionic 2.

  • I did same as you have mentioned it in installation section.
  • Also import that in www/lib
  • gave appropriate path in index.html

but It did not work for me, because issue is-
ionic use ionic native and typescript.

How to get this working in ionic 2?

Dependency with ionic from npm instead of bower

There is a dependency towards ionic in bower.
However, now that ionic is only maintained with npm (not anymore with bower), I have ionic installed with npm. How do I do to ignore the ionic depenency in bower?

Android bug even with <preference name="AndroidPersistentFileLocation" value="Internal" />

Hi,

Thank you for your nice plugin that works perfectly on iOs and Webview, but does not load images on Android...
I tried with the recommended setting, but no chance, exactly the same.

It seems some images are loaded (but not displayed), because as i click on an area where the image should be (just a border with nothing inside), the image shows up in big size (that the normal behavior in my app). But some other don't even display this empty border and images don't seem to be
downloaded...

No error displays...

Any idea ?
thank you very much

Cache Expiry

Is there a way to set a cache expiration (don't see it, sorry)?

Trigger the download with a button

Instead of downloading automatically observing the cache-src tag, is it possible to trigger the download manually? I want to choose what will be stored.

Progress circle fake?

I look at the docs and it mentions this

Custom the progress circle
it accepts all options for angular-svg-round-progressbar , except for current

So I presume your progress circle is actually fake?

One more question, my images loaded into the ngStorage are still in http:// format and not file:// format. Do I need to configure anything to make this work? Thanks.

Problem with getCacheDir() method

Looks like there is problem with the method call getCacheDir() in cacheSrcStorage.It is returning undefined instead of data directory.

Also, a question not directly related though. Is it possible to make caching directory configurable. For e.g. in our case it makes more sense to us $window.cordova.file.externalDataDirectory instead of $window.cordova.file.dataDirectory as we want users to browse the content of images cache.

Root Cause:
It looks like using var declaration on https://github.com/BenBBear/ionic-cache-src/blob/master/ionic-cache-src.js#L248 is making scope confine to only cacheSrc directive and hence preventing if from being used elsewhere (e.g. https://github.com/BenBBear/ionic-cache-src/blob/master/ionic-cache-src.js#L174).

Can't load or cache more than one image per view.

I had images loading from Firebase Storage via the url their service provides when the image is saved there.

I've added ionic-cache-src per the docs and added the encode-uri="false" with each image tag. What I'm finding is that on initial page load, if I have two images in the view, the one furthest from the top of the page gets cached and loaded fine. But the first does not cache properly and does not get loaded.

Instead first images get saved in a subdirectory within file://data/data/com.ionicframework.pta755557/files as shown below
screen shot 2016-08-12 at 3

So files arLXK... and zWe4N... display those inside WcVDX... sOOFc... directories do not.

collection-repeat使用时候会出现bug

collection-repeat使用时候会出现bug. 只要使用collection-repeat 读取缓存图片就会不对了,图片全乱了。collection-repeat使用 ion-infinite-scroll拉数据bug比较严重。单独使用ng-src不会有问题,一使用cache-src就出先图片和其他图片对调全乱了。

Dynamic source breaks when changed during loading

When using a dynamic source image which changes fast and the images aren't cached yet(!), occasionally the wrong image gets cached for the wrong url. I tried to find out how i can solve this myself by looking through the code but didn't manage to find a solution.
Can anybode help me with this issue?

Image not loading when cache-src expression changes using watch instead of observe

Hi,
When you did your update "support video/audio, bug fixes for several issues" you changed observe to watch. Since then when i have an expression like this
cache-src={{::somevariable}}
The image fails to load when the value of somevariable is set some time after the view has loaded.
I also tried it without angular one time binding (the ::) but i still couldn't get the image to load.
When i reverted back to observe, everything worked again.

Thanks,

Matt

iOS - Cached images not found

Hi,

where exactly does this plugin store the files on iOS?

I use var localUrl = cordova.file.dataDirectory; what resolves to file:///var/mobile/Containers/Data/Application/<UUID>/Library/NoCloud/

If the device is offline I receive this error:

Failed to load resource: file:///var/mobile/Containers/Data/Application/<UUID>/Library/NoCloud/eroq1wz4bJTzfEbT.jpg
The requested URL was not found on this server.

On Android all works fine.

On top I had to change the code block starting at: https://github.com/BenBBear/ionic-cache-src/blob/master/ionic-cache-src.js#L169

to avoid returning undefined:

c.get = function(url) {
    var result = undefined;
    if (needDownload(url)) {
        var cache_url = c._cache[url] && (getCacheDir() + c._cache[url]);
        result = cache_url || url;
    }
    return result;
};

Thanks for your advice(s).

Fallback image

I could not find any way to add fallback image if error download image happened. Could anyone point me out please?

Minification issue

Hi,

Once again thanks for taking the time to create this plugin, it really has been a life saver for me. I am in the process of taking my app into production mode so I started looking into minifcation of my code. I used the ng-strict-d attribute to get angular to throw errors when a function was not minifcation safe and it showed some functions inside of img-cache-src.js. Specifically .factory('cacheSrcStorage'... and .directive('cacheSrc'.....

I used the array notation on these and now and that seems to have fixed everything, i.e.

.factory('cacheSrcStorage',['$localStorage', function($localStorage) {.....}])

and

.directive('cacheSrc',["$ionicPlatform", "$window", "$interval", "$timeout", "$compile", "$cacheSrc", "$cordovaFileTransfer", "$localStorage", function($ionicPlatform, $window, $interval, $timeout, $compile, $cacheSrc, $cordovaFileTransfer, $localStorage) {....}])

It could be worth updating your code to include this.

Matt

Dynamic url images break in iOS.

I've images from S3 , when i try to cache it with the ionic-cache-src , some of the images seems to be broken. It is working fine in Android.

I'm loading the images in ng-repeat

screen shot 2016-05-20 at 10 57 39 am

Won't work for video tags

I can't seem to make this work for video tags, it seems to me that the code should work for HTML5 video as well as images, but no amount of fiddling seems to get it to work. Any ideas what I am doing wrong or how I can make it work with video.

Thanks, great idea.

'cache-src' since it isn't a known property of 'source'

core.js:1449 ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'cache-src' since it isn't a known property of 'source'. ("
poster="{{data.img[0]}}">

  <source [ERROR ->]cache-src="{{data.video}}" type="video/mp4">

</video>

Doesn't work on launch

Dear Ben,

When I launch the app on Android it doesn't work, I have to go to an other view and then come back it just after that it works fine all the time ! But how to make it works from the beginning ?

For iOS, it never works... I correctly activate the "NSAppTransportSecurity", but still same issue : I just have the loader that appears and doesn't start.

What do you suggest ?

Thanks in advance

To

Preload images when the app is launched

Hello,

I would like to load the images in cache when the app is launched so that when the user open some screen the images are already loaded.
Can I use:
module.controller('Ctrl', function(cacheSrcStorage) {
cacheSrcStorage.get('url') // === the local cache path for 'url'
});

Module does not exist in my app, what should I call instead?
instead of 'get' I put 'set'?
Thanks,

Problems with dynamic source

Hi, I have a problem with using dynamic source.
My app's idea is to go to firebase and retrieve an array of links of videos, and play the videos one by one like a playlist.
Using ionic-cache-src, even if the device is offline, videos can still be played (the links are stored in local storage when they are retrieved from firebase, so even if it's in offline state, the links are still available)
Now the problem is, when I test the app in a web browser, everything works well as expected even when the device is offline. But when I try to deploy on a device, the videos can't be loaded when it's offline.

        <video autoplay ui-event="{ended:'next()'}">
          <source cache-src="{{link}}" type="video/mp4">
        </video>

One more thing, when the "{{link}}" part is changed to the actual url of the video, it works perfectly.
Thanks for help!

plugin not working with minification

hi,

the plugin is really great but is not working in production when my files are minified because you didn't inject depencies the angular way or used something like ng anotate, thus, i can't use it :/

are you planning to fix it someday ? thanks

Doesn't Run on Device

Works fine as 'ionic serve -l', but same code shows no images at all when loaded on a real device (Android Nexus 6).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.