Last active
January 2, 2017 16:48
-
-
Save elct9620/5b186d2e693b5e7e5984b22ff9bd50bc to your computer and use it in GitHub Desktop.
This file contains 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 UnityEditor; | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UniRx; | |
public class DatabaseDownloader { | |
public static string DatabaseURL = "SERVER_URL"; | |
private const string Token = "TOKEN"; | |
public static void LoadDatabase(string Query, Action<Dictionary<string, string>> Parser) { | |
UriBuilder _Uri = new UriBuilder(DatabaseURL); | |
_Uri.Query = Query + string.Format("&token={0}", Token); | |
EditorUtility.DisplayDialog ("讀取資料庫", "開始下載資料", "確定"); | |
Observable.FromCoroutine<int> ((observer, cancellationToken) => GetDatabase (_Uri.ToString (), Parser, observer, cancellationToken)) | |
.Subscribe (count => { | |
if(count == -1) { | |
EditorUtility.DisplayDialog("下載失敗", "下載資料庫失敗", "確定"); | |
} else { | |
EditorUtility.DisplayDialog("下載成功", string.Format("已下載 {0} 筆資料", count), "確定"); | |
} | |
}); | |
} | |
static int CreateDatabase(string Response, Action<Dictionary<string, string>> Parser) { | |
JSONObject RawData = new JSONObject (Response); | |
if (RawData.type == JSONObject.Type.ARRAY) { | |
Dictionary<string, string> _item; | |
foreach (JSONObject item in RawData.list) { | |
_item = item.ToDictionary (); | |
Parser (_item); | |
} | |
return RawData.list.Count; | |
} | |
return -1; | |
} | |
static IEnumerator GetDatabase(string url, Action<Dictionary<string, string>> Parser, IObserver<int> observer, CancellationToken cancellationToken) { | |
WWW www = new WWW (url); | |
while (!www.isDone && !cancellationToken.IsCancellationRequested) { | |
yield return null; | |
} | |
if(cancellationToken.IsCancellationRequested) { | |
yield break; | |
} | |
if (www.error != null) { | |
observer.OnError (new Exception (www.error)); | |
} else { | |
observer.OnNext (CreateDatabase (www.text, Parser)); | |
observer.OnCompleted (); | |
} | |
} | |
} |
This file contains 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
[ | |
{ | |
"編號": 1, | |
"名稱": "Example", | |
... | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment