【问题标题】:Catching errors loading Remote Images in Titanium ImageView在 Titanium ImageView 中加载远程图像时捕获错误
【发布时间】:2014-12-18 03:31:11
【问题描述】:

我正在使用 Titanium SDK 3.4.0 GA,开发一个将远程图像从我的网络服务器加载到 ImageView 的 Android 应用程序。

当设备在加载该图像期间失去连接时出现问题,因此,我需要一种方法来捕获该错误(超时,404 ...)并设置“imageNotAvailable”。 我正在为 MacOSX 使用 Network Link Conditioner 来重现该场景,延迟低,数据包丢失...

为了证明这一点,我在我的 test.js(合金控制器)中使用了以下代码,并在我的 test.xml 中使用了一个带有 id='imageView' 的 ImageView 的简单 view

有时会抛出异常:

TiDownloadManager: (pool-4-thread-1) [45929,118581] 异常下载 http://...

但并非总是如此(远程连接超时似乎无限),无论如何,有这个异常,没有这个我无法捕捉到这个(可能是由于异步请求)也不会触发 ERROR 事件。

function imageNotAvailable(e)
{       
    Ti.API.info('Error loading image:'+JSON.stringify(e));
    $.imageView.image = "/imageNotAvailable.png";
}

function onLoad(e)
{
    Ti.API.info('Image Loaded:'+JSON.stringify(e));
}

function setImageAndroid(image)
{
    try{
        $.imageView.image = 'http://....';
    }catch(e){
        $.imageView.fireEvent("error");
    }

    $.imageView.addEventListener("error", imageNotAvailable);
    $.imageView.addEventListener("load", onLoad);

}

请原谅我的英语不好!谢谢!

【问题讨论】:

    标签: android appcelerator titanium-alloy


    【解决方案1】:

    您是否尝试在设置 imageView 的图像属性之前添加事件侦听器?

    【讨论】:

      【解决方案2】:

      我可以建议一种使用 http 请求的方法

      在某个库类中创建一个函数,该函数接受您应该点击的 url

      Connection.getImage = function(link){
      var xhr = Titanium.Network.createHTTPClient({
                  onload : function(e) {
                      var responseResult = this.responseText;
                      callback(responseResult);
                  },
                  // function called when an error occurs, including a timeout
                  onerror : function(e) {
                      callback("fail");
                      // Ti.API.info('IN ERROR ' + e.error);
                  },
               timeout : 5000
              });
      
          xhr.open("GET", link);
      xhr.send();
      };
      

      // ps 您将收到一个 blob 作为响应,您可以将其附加到 imageView.blob 属性,它会建议使用默认图像作为占位符,直到您获得成功响应。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-11
        • 1970-01-01
        • 2016-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多