Created
August 13, 2012 03:53
-
-
Save asus4/3336838 to your computer and use it in GitHub Desktop.
cache system for unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System; | |
using System.Collections; | |
using System.IO; | |
/// <summary> | |
/// WWW cache. | |
/// </summary> | |
public class WWWCache { | |
static string strToBase64 (string str) | |
{ | |
//Debug.Log(str); | |
byte[] byt = System.Text.Encoding.UTF8.GetBytes (str); | |
return Convert.ToBase64String (byt); | |
} | |
static string base64ToStr (string base64) | |
{ | |
byte[] b = Convert.FromBase64String (base64); | |
return System.Text.Encoding.UTF8.GetString (b); | |
} | |
public static string UrlToCachePath (string url) | |
{ | |
return Application.persistentDataPath + "/" + strToBase64 (url); | |
} | |
public static bool HasCache (string url) | |
{ | |
return File.Exists (UrlToCachePath (url)); | |
} | |
/// <summary> | |
/// Write to cache file | |
/// </summary> | |
/// <returns> | |
/// is success | |
/// </returns> | |
/// <param name='url'> | |
/// url | |
/// </param> | |
/// <param name='bytes'> | |
/// data | |
/// </param> | |
public static bool WriteCache (string url, byte[] bytes) | |
{ | |
//Debug.LogWarning("url:"+url); | |
//Debug.Log("path:"+urlToCachePath(url)); | |
long freeSpace = DiskSpace.FreeSpece; | |
if (freeSpace < -1) { | |
freeSpace = Math.Abs (freeSpace); | |
} | |
if (freeSpace <= bytes.Length && freeSpace >= -1) { | |
return false; | |
} | |
bool success = false; | |
try { | |
File.WriteAllBytes (UrlToCachePath (url), bytes); | |
success = true; | |
} catch { | |
Debug.LogError ("file save error"); | |
success = false; | |
} finally { | |
} | |
return success; | |
} | |
/// <summary> | |
/// Delete cached file | |
/// </summary> | |
/// <returns> | |
/// is successed | |
/// </returns> | |
/// <param name='url'> | |
/// cached file URL | |
/// </param> | |
public static bool DeleteCache (string url) | |
{ | |
string path = UrlToCachePath (url); | |
if (!File.Exists (path)) { | |
return false; | |
} else { | |
try { | |
File.Delete (path); | |
} catch (Exception ex) { | |
Debug.LogWarning (ex); | |
return false; | |
} | |
} | |
return true; | |
} | |
public static string CacheUrl(string url) { | |
string path = UrlToCachePath(url); | |
//Debug.LogWarning(data_path +" : "+path); | |
if(File.Exists(path)) { | |
return "file://" + path; | |
} | |
return ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment