Creating and retrieving a file from an iOS device with Unity3

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!

2 thoughts on “Creating and retrieving a file from an iOS device with Unity3

  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About

This is PlayMedusa's game devlog: sketches, artwork, news, tutorials... Know more about us and our work in our MAIN SITE!

We create games mostly because we enjoy doing so. We hope you also enjoy playing them! Check them out at itchio Some can be played on the browser!

Este sitio web utiliza cookies para que usted tenga la mejor experiencia de usuario. Si continúa navegando está dando su consentimiento para la aceptación de las mencionadas cookies y la aceptación de nuestra política de cookies, pinche el enlace para mayor información.plugin cookies

ACEPTAR
Aviso de cookies