Version: 2019.3
Construyendo Plugins para iOS
Customising WWW requests on iOS

Preparing your application for In-App Purchases (IAP)

Este capitulo no describe cómo integrar su juego con el API StoreKit de Apple. Es asumido que usted ya tiene integración con StoreKit vía un plugin de código nativo.

The Apple StoreKit documentation defines four kinds of products that can be sold via the In-App Purchase process:

  • Contenido
  • Funcionalidad
  • Servicios
  • Subscripciones

Este capitulo cubre el primer caso solamente y se centrar principalmente en el concepto de contenido descargable. AssetBundles son recomendados para implementar contenido descargable en Unity y ambas las creación y el uso de tiempo de ejecución de los AssetBundles serán cubiertos aquí.

Exportando sus assets para uso en iOS

A veces es más útil mantener proyectos separados para su aplicación principal y los AssetBundles descargables que va a utilizar. Sin embargo, usted debería tener en cuenta que todos los scripts referenciados por objetos en el AssetBundle deben estar presente en el ejecutable principal de juego. El proyecto que usted utilice para crear el AssetBundle debe tener iOS seleccionado como el objeto de construcción debido a que el contenido de los archivos AssetBundle no es compatible entre iOS y otras plataformas.

AssetBundles are created using editor scripts - a simple example is given below:

using UnityEngine;
using UnityEditor;

public class ExportBundle : MonoBehaviour {
    [MenuItem ("Assets/Build AssetBundle From Selection - Track dependencies")]
    static void DoExport() {
        string str = EditorUtility.SaveFilePanel("Save Bundle...", Application.dataPath, Selection.activeObject.name, "assetbundle");
        if (str.Length != 0) {
            BuildPipeline.BuildAssetBundle(Selection.activeObject, Selection.objects, str, BuildAssetBundleOptions.CompleteAssets, BuildTarget.iPhone);
        }
    }
}

You should save this code in a file called ExportBundle and place it inside a folder called Editor (you can just create this if it isn’t already present in the project). The script will add a menu item entitled Build AssetBundle From Selection - Track dependencies on the Assets menu in the editor.

The content you want to include in the bundle should be prepared in the form of prefabs. Select a prefab in the Project view and then select Assets > Build AssetBundle From Selection - Track dependencies (i.e. the menu item added by the ExportBundle script). This command will bring up a save dialog where you can choose the name and location of your AssetBundle file.

Descargando sus assets en iOS

Note: Apple may change the folder locations where you are permitted to write data. Always check the latest Apple documentation to be sure your application will be compliant. The following advice was correct as of early 2018.

AssetBundles can be downloaded using the WWW class and once transfer is complete, the enclosed assets can be accessed. The recommended way to download an AssetBundle is to use LoadFromCacheOrDownload as shown in the following sample:

IEnumerator GetAssetBundle() {
    WWW download;
    string url = "http://somehost/somepath/someassetbundle.assetbundle";

    while (!Caching.ready)
        yield return null;

    download = WWW.LoadFromCacheOrDownload(url, 0);

    yield return download;

    AssetBundle assetBundle = download.assetBundle;
    if (assetBundle != null) {
        // Alternatively you can also load an asset by name (assetBundle.Load("my asset name"))
        Object go = assetBundle.mainAsset;
            
        if (go != null)
            Instantiate(go);
        else
            Debug.Log("Couldn't load resource");    
    } else {
        Debug.Log("Couldn't load resource");    
    }
}

The downloaded asset bundle files are stored in the Library folder of the iOS application sandbox and have the No Backup flag set on them. This means the OS won’t delete these files accidentally and these files won’t be backed up to iCloud.

If you need to choose exactly where the AssetBundle file is stored, you can use a standard WWW download (i.e. just use the constructor instead of LoadFromCacheOrDownload) and then save the downloaded data on disk using the .NET file API. You can save required files to the Application.temporaryCachePath folder (stored in Library/Caches which is regularly “cleaned out” by the OS) or the Application.persistentDataPath folder (stored in Documents which is not cleaned out by the OS). You should set the No Backup flag on these files with iOS.Device.SetNoBackupFlag to prevent them being backed up to iCloud.

Tenga en cuenta: Si usted no tiene configurada la flag No Backup, su aplicación puede ser rechazada cuando usted la publique a la App Store.

Usted puede acceder a los archivos guardados creando un objeto WWW con el URL de la forma file:///pathtoyourapplication/Library/savedassetbundle.assetbundle:-

string cachedAssetBundle = Application.temporaryCachePath + "/savedassetbundle.assetbundle"; 
System.IO.FileStream cache = new System.IO.FileStream(cachedAssetBundle, System.IO.FileMode.Create);
cache.Write(download.bytes, 0, download.bytes.Length);
cache.Close();

iOS.Device.SetNoBackupFlag(cachedAssetBundle);

Debug.Log("Cache saved: " + cachedAssetBundle);

Note: You can test the reading of stored files in the Documents folder if you enable file sharing (setting UIFileSharingEnabled to true in your Info.plist allows you to access the Documents folder from iTunes). Note that the contents of the Documents folder are cached to iCloud, so you should not use this location to store AssetBundles in the final build to be shipped. See File System Basics in the Apple iOS documentation for further details.


  • 2018–06–14 Page amended
Construyendo Plugins para iOS
Customising WWW requests on iOS