在Unity iOS上打开设置应用程序。

4

我需要一种方法,使用户可以进入设置应用程序来禁用多任务手势。我知道在iOS 8中,你可以通过Objective-C中的URL编程方式启动设置应用程序:

NSURL * url = [NSURL URLWithString: UIApplicationOpenSettingsURLString];

但我不知道如何在Unity中获取此URL以便与Application.OpenURL()一起使用。


请不要在与Unity游戏引擎相关的问题中使用“unity”标签。在使用标签之前,通常最好先阅读标签的描述。 - Max Yankov
抱歉,下次我会更加注意。 - Gilian
2个回答

12

你需要为此编写一个小型的iOS插件,这里提供更多相关信息:http://docs.unity3d.com/Manual/PluginsForIOS.html

以下是解决方案,请在有疑问时询问。

Script/Example.cs

using UnityEngine;

public class Example 
{
    public void OpenSettings()
    {
        #if UNITY_IPHONE
            string url = MyNativeBindings.GetSettingsURL();
            Debug.Log("the settings url is:" + url);
            Application.OpenURL(url);
        #endif
    }
}

插件/MyNativeBindings.cs

public class MyNativeBindings 
{
    #if UNITY_IPHONE
        [DllImport ("__Internal")]
        public static extern string GetSettingsURL();

        [DllImport ("__Internal")]
        public static extern void OpenSettings();
    #endif
}

插件/iOS/MyNativeBindings.mm

extern "C" {
    // Helper method to create C string copy
    char* MakeStringCopy (NSString* nsstring)
    {
        if (nsstring == NULL) {
            return NULL;
        }
        // convert from NSString to char with utf8 encoding
        const char* string = [nsstring cStringUsingEncoding:NSUTF8StringEncoding];
        if (string == NULL) {
            return NULL;
        }

        // create char copy with malloc and strcpy
        char* res = (char*)malloc(strlen(string) + 1);
        strcpy(res, string);
        return res;
    }

    const char* GetSettingsURL () {
         NSURL * url = [NSURL URLWithString: UIApplicationOpenSettingsURLString];
         return MakeStringCopy(url.absoluteString);
    }

    void OpenSettings () {
        NSURL * url = [NSURL URLWithString: UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL: url];
    }
}

我还将尝试打印此URL以获取它,并与Application.OpenURL()一起使用,以避免使用插件 ;) - Gilian
可以使用Application.OpenURL()打印URL并打开它,但是仍然需要插件来获取URL,因为苹果可能会更改URL,如果使用硬编码的URL,您的应用程序将会崩溃。(我明天会分享那段代码) - JeanLuc
我添加了一个GetSettingsURL()方法。 - JeanLuc
我会接受你的答案,谢谢。希望Unity团队能够提供一种在C#中获取此URL的方法。 - Gilian
我认为Unity团队不会添加这个功能,因为他们不喜欢平台特定的代码。 - JeanLuc

3
使用JeanLuc的想法,我创建了一个空的XCode项目,并打印了字符串常量UIApplicationOpenSettingsURLString,然后在Unity中使用Application.OpenURL()函数来避免使用插件。非常好用。
常量UIApplicationOpenSettingsURLString的值为:"app-settings:"(不含引号)。
使用Application.OpenURL("app-settings:")可以直接从Unity打开。
警告:硬编码字符串是危险的,如果苹果更改了常量UIApplicationOpenSettingsURLString的值,可能会破坏您的代码。这只是一种解决方法,因为Unity没有在C#代码中添加常量的参考。

这是正确的答案。不需要制作插件。只需使用“Application.OpenURL(“ app-settings:“)”。 - gravy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接