Unity iOS 应用图像缓存问题



我已经接管了一个完整的应用程序的开发,减去需要互联网连接才能加载图像的错误,因为它不会从缓存中访问它们,尽管尝试这样做。

谁能帮我弄清楚下面出了什么问题?

public class SpriteCache : Singleton<SpriteCache>
{
Dictionary<string, Sprite> _cache = new Dictionary<string, Sprite>();
public void LoadSprite(string url, Action<Sprite> callback)
{
StartCoroutine(LoadSpriteCoroutine(url, callback));
}
public IEnumerator LoadSpriteCoroutine(string url, Action<Sprite> callback)
{
if (_cache.ContainsKey(url))
{
callback(_cache[url]);
yield break;
}
var www = new WWW(url);
while (!www.isDone)
{
yield return www;
}
if (!string.IsNullOrEmpty(www.error))
{
Debug.LogErrorFormat("Tried to obtain texture at '{0}' but received error '{1}'", url, www.error);
yield break;
}
var texture = www.texture;
if (texture == null)
{
Debug.LogErrorFormat("No texture found at '{0}'!", url);
yield break;
}
var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(texture.width / 2, texture.height / 2));
_cache[url] = sprite;
callback(sprite);
}

编辑:

进一步解释以澄清

var www = new WWW(url)

这抓取存储在正常工作的服务器上的图像,据我所知,在抓取图像的一个实例之后,这应该将该项目放在缓存中以供以后使用。

我尝试使用以下更新的方法查看是否可以修复它。

var www = WWW.LoadFromCacheOrDownload(url, 1)

这导致它无法以任何身份工作,并且永远不会更改占位符中的图像。

"LoadSpriteCoroutine"中的第一个if语句应该通过检查url是否有键来捕获"_cache"字典中是否已经存在精灵,该键应该在第一个运行实例之后具有互联网连接

从_cache加载图像(如果它在那里):

if (_cache.ContainsKey(url))
{
callback(_cache[url]);
yield break;
}

将图像添加到_cache(如果它以前没有

):
var sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(texture.width / 2, texture.height / 2));
_cache[url] = sprite;

所以我想出了一个解决方案,

所有其他将图像保存到缓存的方法似乎都失败了,我删除了所有以前的"_cache"内容。

这个保存功能对我有用:

//if file doesn't exist then save it for fututre reference
if (!File.Exists(_FileLocation + texName))
{
byte[] bytes;
if (Path.GetExtension(texName) == ".png")
{
bytes = texture.EncodeToPNG();
}
else
{
bytes = texture.EncodeToJPG();
}
File.WriteAllBytes(Application.persistentDataPath + texName, bytes);
}

该部分放在"回调(精灵)"之后。

对已保存项目的检查放置在旧的"if(_cache.包含密钥(网址))"部分是

texName = Path.GetFileName(texName);
if (File.Exists( _FileLocation + texName))
{
url = _FileLocation + "/"+ texName;
}

请注意,"LoadSpriteCoroutine"现在在其调用中采用额外的字符串参数"texName",它只是URL的缩短实例,然后它只剪切到文件名和扩展名。如果它找到匹配项,那么它会用持久文件路径 + 文件名替换 url 以在本地获取它,而不是像往常一样通过网络。

_FileLocation定义如下

string _FileLocation;
public void Start()
{
_FileLocation = Application.persistentDataPath;
}

在该方法中引用它的原因是为了节省通过应用程序调用地址的性能,如果您正在处理跨平台解决方案,则可能需要更改用于保存的数据路径,因此您可以放置检测 if 或 case 语句来更改_FileLocation以满足您的需求。

最新更新