Use native code on iOS with Unity Native Code in the Unity

First, write native code you used for iOS. Read this document

I needed to write native code for the In-App Purchase on iOS.

Then, just put your native code in the Assets/Plugins/iOS directory. The hierarchy like this;

For example, using Objective-C, Assets/Plugins/iOS/sample.m and Assets/Plugins/iOS/sample.h.

Build on Unity

In File > Build Settings, switch iOS platform and then click Build and Run. Next, when the build complete, launch Xcode and build the project created by Unity on it automatically.

Build on Xcode

Initial build might occur a signing problem that is Team is None. To solve this problem, just select a team in the pull-down menu of the team. Automatically sign to your app as the team you selected.

Click the build button top left of the Xcode window!

Receive a callback as JSON from an iOS code

Set Game Object on a Unity script before call the native code

var gameObject = GameObject.Find("PurchaseHandler");
            if (gameObject != null) return;

            gameObject = new GameObject("PurchaseHandler");
            if (UnityEngine.Application.isPlaying)
            {
                GameObject.DontDestroyOnLoad(gameObject);
            }

            gameObject.AddComponent<PurchaseHandler>();

Call UnitySendMessage on iOS

sample.m

void GetProductList(const char* json)
{
    ...
    NSString *jsonString = @"{list: [ ... ]}"
    UnitySendMessage([@"PurchaseHandler" UTF8String], [@"onSuccess" UTF8String], [jsonString UTF8String]);
}

Receive a message of UnitySendMessage

public class PurchaseHandler : MonoBehaviour
    {
         private IEnumerator onSuccess(string message)
        {
            yield return doSomething(message);
        }
}

Leave a Reply

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