加载文件下载在Unity中创建的iOS应用程序

时间:2016-10-21 15:16:00

标签: c# ios json xcode unity3d

我试图加载下载并保存在iOS设备的persistentDataPath中的json文件。下载和保存工作得很好。但是我认为加载文件有很大问题。事实上,当我尝试在Xcode中编译项目时,我有一些错误消息。

首先是我的C#代码:

using UnityEngine;
using System.Collections;
using System.IO;
using System.Net;
using UnityEngine.UI;

public class ReadJson : MonoBehaviour
{
    public Text City;
    public Text Temperature;
    public Image Weather;
    public Text WeatherUrl;

    [System.Serializable]
    public class CityInfo 
    {
        public string name;
    }

    [System.Serializable]
    public class CurrentCondition
    {
        public string date; 
        public string hour; 
        public int tmp; 
        public int wnd_spd; 
        public int wnd_gust; 
        public string wnd_dir; 
        public double pressure; 
        public int humidity; 
        public string condition; 
        public string icon; 
        public string icon_big;
    }

    [System.Serializable]
    public class RootObject
    {
        public CityInfo city_info;
        public CurrentCondition current_condition;
    }

    void Start () {

        WebClient client = new WebClient();
        File.Delete(Path.Combine (Application.persistentDataPath, "myjson.json"));
        client.DownloadFile ("http://www.myjsonurl", Path.Combine (Application.persistentDataPath, "myjson.json"));

        TextAsset asset = Resources.Load (Path.Combine (Application.dataPath + "/Documents", "myjson")) as TextAsset;

        RootObject m = JsonUtility.FromJson<RootObject> (asset.text);

        City.text = m.city_info.name;
        Temperature.text = (m.current_condition.tmp).ToString();

    }
}

现在是xcode控制台:

2016-10-21 17:01:20.766001 json[1404:516674] [DYMTLInitPlatform] platform initialization successful

2016-10-21 17:01:20.929950 json[1404:516508] -> registered mono modules 0xb95f70
2016-10-21 17:01:21.356590 json[1404:516508] You've implemented -[<UIApplicationDelegate> application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist.
-> applicationDidFinishLaunching()
2016-10-21 17:01:21.452967 json[1404:516508] Metal GPU Frame Capture Enabled
2016-10-21 17:01:21.453369 json[1404:516508] Metal API Validation Enabled
-> applicationDidBecomeActive()
Init: screen size 750x1334
Initializing Metal device caps
Initialize engine version: 5.3.4f1 (fdbb5133b820)
UnloadTime: 1.705875 ms
Salut/var/mobile/Containers/Data/Application/51A2490E-94EB-4904-9F2E-112AD5632A98/Documents

(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 37)

NullReferenceException: A null value was found where an object instance was required.


(Filename: currently not available on il2cpp Line: -1)

Setting up 1 worker threads for Enlighten.
  Thread -> id: 19f17000 -> priority: 1 

如果有人有想法。非常感谢。

1 个答案:

答案 0 :(得分:1)

您的代码存在问题:

TextAsset asset = Resources.Load(Path.Combine(Application.dataPath + "/Documents", "myjson")) as TextAsset;

我认为您不了解如何以及何时使用Resources.Load。如果要使用Resources.Load功能,则必须从编辑器创建一个特殊文件夹。此文件夹应位于<ProjectDirectory>/Assets/Resources。您可以 从编辑器中将内容放入/写入此文件夹。在iOS上构建后你无法做到这一点。构建它后,它变为只读。然后可以使用Resources.Load功能读取此特殊文件夹。

更换:

TextAsset asset = Resources.Load(Path.Combine(Application.dataPath + "/Documents", "myjson")) as TextAsset;

string text = File.ReadAllText(Path.Combine(Application.persistentDataPath, "myjson.json"));
RootObject m = JsonUtility.FromJson<RootObject>(text);
City.text = m.city_info.name;
Temperature.text = (m.current_condition.tmp).ToString();

应该解决你的问题。

另一个不应使用的API是WebClient。除非你有充分的理由使用它,否则你不应该这样做。您应该使用WWWUnityWebRequest(更新和推荐的)API。

这是您的代码在没有WebClient的情况下的样子:

void Start()
{
    StartCoroutine(DownloadAndloadJson());
}

IEnumerator DownloadAndloadJson()
{
    string url = "http://www.myjsonurl";

    UnityWebRequest www = UnityWebRequest.Get(url);
    yield return www.Send();

    if (www.isError)
    {
        Debug.Log(www.error);
    }
    else
    {
        //Sucessfully downloaded the Json File
        Debug.Log("Json: " + www.downloadHandler.text);

        string jsonFile = www.downloadHandler.text;

        //Delete old json file. Don't know why but this was in your original code
        File.Delete(Path.Combine(Application.persistentDataPath, "myjson.json"));

        //Save the downloaded data as File
        File.WriteAllText(Path.Combine(Application.persistentDataPath, "myjson.json"), jsonFile);

        //Load the downloaded data 
        string text = File.ReadAllText(Path.Combine(Application.persistentDataPath, "myjson.json"));

        Debug.Log(text);
        RootObject m = JsonUtility.FromJson<RootObject>(text);
        City.text = m.city_info.name;
        Temperature.text = (m.current_condition.tmp).ToString();
    }
}

如果您遇到问题,请更新到Unity 5.4。应该使用UnityWebRequest API,它在5.3中引入,但错误在5.4中得到修复。您需要using UnityEngine.Networking;才能使用UnityWebRequest