问题
最近接FirebaseCloudMessage时遇到一个问题:获取deviceToken的回调函数不执行,导致设置token失败。
原因
Unity通过宏“UNITY_USES_REMOTE_NOTIFICATIONS”对回调做了限制。在5.x之前的版本这个宏默认是开着的,在2017版本之后宏默关了。
解决方案
把宏 UNITY_USES_REMOTE_NOTIFICATIONS 的默认值改为1即可。代码位于Preprocessor.h,Unity部分源代码如下:
// An highlighted block
#define UNITY_USES_REMOTE_NOTIFICATIONS 1
#define UNITY_USES_WEBCAM 0
#define UNITY_USES_MICROPHONE 0
#define UNITY_USES_REPLAY_KIT 0
#define UNITY_USES_DYNAMIC_PLAYER_LIB 0
#define UNITY_USES_LOCATION 0
#define UNITY_USES_GLES 0
#define UNITY_USES_IAD 0
#define UNITY_SNAPSHOT_VIEW_ON_APPLICATION_PAUSE 0
#define UNITY_DEVELOPER_BUILD 0
#define USE_IL2CPP_PCH 0
#define UNITY_SUPPORT_ROTATION PLATFORM_IOS
#if PLATFORM_TVOS
#define UNITY_TVOS_ORIENTATION landscapeLeft
#endif
正式开发中当然不可手动修改,所以需要写一下代码:
#if UNITY_IOS
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.iOS.Xcode;
using UnityEngine;
public class XCodeProcess
{
[PostProcessBuild]
public static void OnPostprocessBuild(BuildTarget buildTarget, string path)
{
if (buildTarget != BuildTarget.iOS)
return;
PatchPreprocessor(path);
}
private static void PatchPreprocessor(string path)
{
var preprocessorPath = path + "/Classes/Preprocessor.h";
var preprocessor = File.ReadAllText(preprocessorPath);
preprocessor =
preprocessor.Replace("UNITY_USES_REMOTE_NOTIFICATIONS 0", "UNITY_USES_REMOTE_NOTIFICATIONS 1");
File.WriteAllText(preprocessorPath, preprocessor);
}
}
#endif
完结撒花