【问题标题】:$cordovaFile not going well with cache of Ionic resulting in showing wrong picture$cordovaFile 与 Ionic 的缓存不兼容导致显示错误的图片
【发布时间】:2016-05-20 08:50:29
【问题描述】:

以下场景

  1. main.admin.emergencyDetail.photos
  2. 加载每张图片并显示为列表视图
  3. 单击列表中的一个图像会打开一个模式,该模式允许使用离子滑块在图像列表中滑动
  4. 回到main.admin.emergencyDetail
  5. 返回main.admin 并从列表中选择新的紧急情况(转到另一个main.admin.emergencyDetail.photos
  6. 从列表中打开照片以模态显示:现在显示的是上次在此视图中显示的旧照片,从现在开始仅显示从第 3 点加载的照片。在每个main.admin.emergencyDetail.photos 状态中显示
  7. 关闭应用程序并重新打开使我能够重置此错误。一旦我到达第 3 点。我现在在每个main.admin.emergencyDetail.photos 状态中打开这张图片

有趣的是:当我检查文件系统file:///data/data/<appname>/cache 时,通过返回一个状态(就像我在 4. 中所做的那样)成功删除了 photoCache 文件夹,这意味着旧图片被 ionic 以某种方式缓存。我想我可以放在某个地方 window.cache.clear() 但不太确定该放在哪里....

'use strict';
angular.module('main')
.controller('AdminEmergencyCtrl', function (Action, $window, $state, $ionicSideMenuDelegate,
                                          $location, $rootScope, $ionicHistory, $timeout,
                                          Rest, $stateParams, $log, uiGmapGoogleMapApi,
                                          $mdToast, $ionicPopup, $ionicModal, $scope,
                                          $ionicSlideBoxDelegate, $cordovaFile, $q) {
// Authenticate
($rootScope.authenticated.state &&
$rootScope.authenticated.type === 'Admin') ? '' : $location.url('main/inactive');

$log.log('Hello from your Controller: AdminEmergencyCtrl in module main:. This is your controller:', this);

// Settings
$rootScope.$broadcast('checkMenuButton', {});
$ionicSideMenuDelegate.canDragContent(true);
$scope.$on('$ionicView.leave', function (scopes, states) {
  document.addEventListener('deviceready', function () {
    $cordovaFile.removeRecursively(cordova.file.cacheDirectory, 'photoCache')
      .then(function (success) {
        $log.log('($ionicView.leave) cacheDirectory/photoCache cleared');
      }, function (error) {
        $log.log('($ionicView.leave) cacheDirectory/photoCache clearing error:');
        $log.log(error);
      });
  }, false);
});

// Initialize values
var ctrl = this;
ctrl.emergency = {};

ctrl.currentUser = Action.getDeviceID();
ctrl.map = {};
ctrl.showMap = ($ionicHistory.currentStateName() === 'main.admin.emergencyDetail');
$scope.$on('$ionicView.enter', function (scopes, sates) {
  // reassign boolean to prevent strange loading behaviour of google maps
  ctrl.showMap = ($ionicHistory.currentStateName() === 'main.admin.emergencyDetail');
});
ctrl.assigned = null;

ctrl.hasImages = false;
ctrl.isLoading = true;
$scope.images = [];
ctrl.marker = {};

// Functions declarations
ctrl.getEmergency = function () {
  Rest.getEmergency($stateParams.id,
    function (success) {
      var data = angular.fromJson(success);
      var lat = data.Lat;
      var long = data.Long;
      ctrl.emergency = data;
      ctrl.assigned = data.HandledByID;
      ctrl.map = {center: {latitude: lat, longitude: long}, zoom: 15};
      ctrl.marker = {
        id: 0,
        coords: {latitude: lat, longitude: long}
      };
      ctrl.showMap = true;
    },
    function (error) {
      $log.log(error);
    });
};

/**
 * Folder creating -> Files creating -> writing in files -> returning promise for further handling
 *
 * @returns {Promise}
 */
ctrl.fillTempFolder = function () {
  return $q(function (resolve, reject) {
    resolve(fillTempFolderSuccess());
  });
};

function fillTempFolderSuccess () {
  $log.log('AM IN ctrl.fillTempFolder');
  document.addEventListener('deviceready', function () {
    $cordovaFile.createDir(cordova.file.cacheDirectory, 'photoCache', true)
      .then(function (success) {
        $log.log('AM IN $cordovaFile.createDir');
        $scope.images.forEach(function (item) {
          var blob = new Blob([Action.convertDataURIToBinary(item.src)], {type: 'image/jpg'});
          $cordovaFile.createFile(cordova.file.cacheDirectory + 'photoCache/', item.name, true).then(
            function (success) {
              $log.log('(CREATE FILE) Success');
              $cordovaFile.writeFile(cordova.file.cacheDirectory + 'photoCache/', item.name, blob, true)
                .then(function (success) {
                  $log.log('(WRITE FILE) Success');
                }, function (error) {
                  $log.log('(WRITE FILE) Error');
                  $log.log(error);
                });
            },
            function (error) {
              $log.log('(CREATE FILE) Error');
              $log.log(error);
            }
          );
        });
      }, function (error) {
        $log.log('(CREATE DIR) Could not write to FileSystem');
      });
  }, false);
}

ctrl.loadPictures = function (lastPic) {
  Rest.getNextPicture($stateParams.id, lastPic,
    function (success) {
      var data = angular.fromJson(success);
      var item = {src: 'data:image/jpg;base64,' + data.Data, name: data.Pic};
      $scope.images.push(item);
      $log.log('pic loaded: ' + data.Pic);
      ctrl.hasImages = true;
      ctrl.loadPictures(data.Pic);
    },
    function (error) {
      ctrl.isLoading = false;
      $log.log(cordova.file.cacheDirectory + 'photoCache/');
      ctrl.fillTempFolder().then(function (success) {
        $timeout(function () {
          $log.log('CREATING MODAL');
          $scope.modal = $ionicModal.fromTemplate(
            '<div class="modal image-modal transparent" ng-click="closeModal()">' +
            '<ion-slide-box on-slide-changed="slideChanged(index)" show-pager="false">' +
            '<ion-slide ng-repeat="oImage in images">' +
            '<img ng-src="' + cordova.file.cacheDirectory + 'photoCache/{{oImage.name}}" class="fullscreen-image" />' +
            '</ion-slide>' +
            '</ion-slide-box>' +
            '</div>', {
              scope: $scope,
              animation: 'slide-in-up'
            });
        }, 3000);
      });
    }
  );
};

ctrl.showPicturesPage = function () {
  $state.go('main.admin.emergencyDetail.photos', {'id': $stateParams.id});
};

$scope.openModal = function () {
  $ionicSlideBoxDelegate.slide(0);
  $scope.modal.show();
};

$scope.closeModal = function () {
  $scope.modal.hide();
};

// Called each time the slide changes
$scope.slideChanged = function (index) {
  $scope.slideIndex = index;
};

// Cleanup the modal when we're done with it!
$scope.$on('$destroy', function () {
  $scope.modal.remove();
});

// Call this functions if you need to manually control the slides
$scope.next = function () {
  $ionicSlideBoxDelegate.next();
};

$scope.previous = function () {
  $ionicSlideBoxDelegate.previous();
};

$scope.goToSlide = function (index) {
  $scope.modal.show();
  $ionicSlideBoxDelegate.slide(index);
};

// Called each time the slide changes
$scope.slideChanged = function (index) {
  $scope.slideIndex = index;
};

// Functions run
if ($ionicHistory.currentStateName() === 'main.admin.emergencyDetail') {
  ctrl.getEmergency();
} else {
  ctrl.loadPictures('');
}
});

【问题讨论】:

    标签: ionic-framework cordova-plugin-file


    【解决方案1】:

    我通过向 ng-src 路径添加时间戳解决了我的问题。

    来源:Stackoverflow - forcing a ng-src reload

    【讨论】:

      猜你喜欢
      • 2016-10-12
      • 1970-01-01
      • 2020-07-19
      • 2020-06-02
      • 2021-10-15
      • 2018-05-04
      • 2018-10-07
      • 2020-04-07
      • 1970-01-01
      相关资源
      最近更新 更多