You may want to collect data with a Unity3 iOS app in a text file for a variety of reasons. How to create and retrieve that file from your iOS device is much simpler than I expected.
Part of the trick consists on using Application.persistentDataPath. According to Unity Script Reference: “Contains the path to a persistent data directory (Read Only). The value is a directory path where data expected to be kept between runs can be stored.”. Best of all: it’s a cross-platform solution. In MacOS it points to /Users/username/Library/Caches/companyname/productname (Company Name and Product Name in Player Settings). In iOS it’s a huge alphanumeric string, but you don’t need it to retrieve your file.
So, first things first. This piece of code creates a dummy text file and prints Application.persistentDataPath on screen. Just for the sake of curiosity.
using UnityEngine; using System.Collections; using System.IO; public class FileIOTest : MonoBehaviour { string FILE_NAME = "dummy_data.txt"; void Start () { string fileName = Application.persistentDataPath + "/" + FILE_NAME; StreamWriter fileWriter = File.CreateText(fileName); fileWriter.WriteLine("Hello world"); fileWriter.Close(); } void OnGUI() { GUI.Label( new Rect(0, 0, 400, 50), Application.persistentDataPath); } }
That’s it. The file is there, somewhere (well, you know exactly where if you run that piece of code and read its output). Now, in XCode, open Info.plist and add a new Key, UIFileSharingEnabled, which in XCode 4.2 looks like this:
Application supports iTunes file sharing – YES
And that’s it. Run the app on your iPhone/iPod/iPad and it will create the text file. Then connect your device to your computer, open iTunes, browse your iOS device, click the Apps tab and you’ll find right in the bottom of the screen the File Sharing box, where your app should be listed. Click on your app et voilà! There’s your file!
How would I be able to call that file so I can view it on my phone? What I want to do is load what’s saved to that file path.
This post is quite old! I’m not sure this applies anymore. Have a look at https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html