GithubHelp home page GithubHelp logo

edricwilliem / unity-firebase-realtime-database Goto Github PK

View Code? Open in Web Editor NEW
40.0 5.0 4.0 99 KB

Unity Firebase Realtime Database REST

Home Page: https://edricwilliem.github.io/unity-firebase-realtime-database/

License: MIT License

C# 96.32% JavaScript 3.68%
unity unity3d firebase firebase-database firebase-realtime-database csharp unity3d-plugin unity-scripts unity-asset unity-plugin

unity-firebase-realtime-database's Introduction

Unity Firebase Realtime Database REST API

Write, Read, Remove and Streaming data using Firebase's database REST API

This is not firebase's official plugins library.

Tested on Android and WebGL platform. should work well on other platforms too since most of the implementation is only a simple http REST request.

Contributions to this project are welcome!.

Sample Usage

Setting Firebase

Before using the library you need to setup some settings in FirebaseSettings.cs

DATABASE_URL = "https://example.firebaseio.com/";
WEB_API = "[WEB_API_KEY]";

Write Data

Set Value:

DatabaseReference reference = FirebaseDatabase.Instance.GetReference("path/to/save");
reference.SetValueAsync("mydata", 10,(res) => 
{
    if (res.success)
    {
        Debug.Log("Write success");
    }
    else
    {
        Debug.Log("Write failed : " + res.message);
    }
});

reference.SetRawJsonValueAsync("{\"key\":\"value\"}", 10,(res) => 
{
    if (res.success)
    {
        Debug.Log("Write success");
    }
    else
    {
        Debug.Log("Write failed : " + res.message);
    }
});

Update Child Value:

DatabaseReference reference = FirebaseDatabase.Instance.GetReference("path/to/save");
reference.UpdateValueAsync(new Dictionary<string, object>(){
    {"child1","value1"},{"child2","value2"}
}, 10, (res) =>
{
    if (res.success)
    {
        Debug.Log("Write success");
    }
    else
    {
        Debug.Log("Write failed : " + res.message);
    }
});

Push Value:

DatabaseReference reference = FirebaseDatabase.Instance.GetReference("path/to/save");
reference.Push("mydata, 10, (res)=>{
    if(res.success){
        Debug.Log("Pushed with id: " + res.data);
    }
    else{
        Debug.Log("Push failed : " + res.message);
    }
});

Read Data

Get Value:

DatabaseReference reference = FirebaseDatabase.Instance.GetReference("path/to/query");
reference.GetValueAsync(10, (res) =>
{
    if (res.success)
    {
        Debug.Log("Success fetched data : " + res.data.GetRawJsonValue());
    }
    else
    {
        Debug.Log("Fetch data failed : " + res.message);
    }
});

Query & Order :

  • OrderByChild
  • OrderByKey
  • OrderByValue
  • StartAt
  • EndAt
  • LimitAtFirst
  • LimitAtLast
DatabaseReference reference = FirebaseDatabase.Instance.GetReference("path/to/query");
reference.OrderByChild("age").StartAt(12).EndAt(20).LimitAtFirst(5).GetValueAsync(10,(res)=>{
        if (res.success)
        {
            Debug.Log("Success fetched data : " +res.data.GetRawJsonValue());
        }
        else
        {
            Debug.Log("Fetch data failed : " + res.message);
        }
});

Delete Data

DatabaseReference reference = FirebaseDatabase.Instance.GetReference("path/to/delete");
reference.RemoveValueAsync(10, (e) =>
{
    if (e.success)
    {
        Debug.Log("Delete data success");
    }
    else{
        Debug.Log("Delete data failed : " + res.message);
    }
});

Streaming Data

DatabaseReference reference = FirebaseDatabase.Instance.GetReference("path/to/stream");
reference.ValueChanged += (sender, e) =>
{
    Debug.Log(e.Snapshot.GetRawJsonValue());
};
reference.DatabaseError += (sender,e)=>{
    Debug.Log(e.DatabaseError.Message);
    Debug.Log("Streaming connection closed");
};

Authentication

Set the credential using saved tokens

FirebaseAuth.Instance.TokenData = new TokenData()
{
    refreshToken = savedRefreshToken,
    idToken = savedAccessToken
};

or Sign In

FirebaseAuth.Instance.SignInWithEmail("[email protected]", "example", 10, (res) =>
{
    if (res.success)
    {
        Debug.Log("Access token : " + res.data.idToken);
    }
    else
    {
        Debug.Log("Signed Failed");
    }
});

after signed in, the FirebaseAuth.Instance.TokenData will be automatically set

FirebaseAuth.Instance.TokenData will be used for authentication on every database's request.

License

MIT

unity-firebase-realtime-database's People

Contributors

edricwilliem avatar galman33 avatar slympp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

unity-firebase-realtime-database's Issues

Stream API returning null

Whenever the path is given and listen is pressed it returns null once... and even when the data of the path is updated nothing happens... Maybe I am doing something wrong. The RealtimeSettings.cs is setup correctly... Please Help

ArgumentNullException is called when trying to stop streaming data

I am currently streaming the user data using this

void SingleUserStream(object sender, ValueChangedEventArgs e)
_singleUserReference.ValueChanged += SingleUserStream;

and when I try to stop the stream using
_singleUserReference.ValueChanged -= SingleUserStream;
I get an

ArgumentNullException: Value cannot be null.
Parameter name: _unity_self
FirebaseREST.DatabaseReference.OnStopListening (UnityEngine.Networking.UnityWebRequestAsyncOperation obj) 
(at Assets/FirebaseREST/Database/DatabaseReference.cs:119)
FirebaseREST.DatabaseReference+<>c__DisplayClass28_1.<BeginListeningServerEvents>b__2 (UnityEngine.AsyncOperation ao) (at Assets/FirebaseREST/Database/DatabaseReference.cs:81)
UnityEngine.AsyncOperation.InvokeCompletionEvent () (at <a979f18d51af41179d12b797e8c5be14>:0)

Problem when building for android platform

Hello thanks for sharing, your library is helpful. But when I try bulding on android for test with il2cpp in unity 2019.4.10(lts) get error below.

Failed running C:\Program Files\Unity\Hub\Editor\2019.4.10f1\Editor\Data\il2cpp/build/deploy/net471/il2cpp.exe --convert-to-cpp --emit-null-checks --enable-array-bounds-check --dotnetprofile="unityaot" --compile-cpp --libil2cpp-static --platform="Android" --architecture="ARMv7" --configuration="Release" --outputpath="D:\UnityProject\unity-firebase-realtime-database-master\Temp\StagingArea\assets\bin\Data\Native\armeabi-v7a\libil2cpp.so" --cachedirectory="D:\UnityProject\unity-firebase-realtime-database-master\Assets\..\Library\il2cpp_android_armeabi-v7a/il2cpp_cache" --additional-include-directories="C:/Program Files/Unity/Hub/Editor/2019.4.10f1/Editor/Data/PlaybackEngines/AndroidPlayer/Tools\bdwgc/include" --additional-include-directories="C:/Program Files/Unity/Hub/Editor/2019.4.10f1/Editor/Data/PlaybackEngines/AndroidPlayer/Tools\libil2cpp/include" --tool-chain-path="C:/Program Files/Unity/Hub/Editor/2019.4.10f1/Editor/Data/PlaybackEngines/AndroidPlayer/NDK" --profiler-report --map-file-parser="C:/Program Files/Unity/Hub/Editor/2019.4.10f1/Editor/Data/Tools/MapFileParser/MapFileParser.exe" --directory=D:/UnityProject/unity-firebase-realtime-database-master/Temp/StagingArea/assets/bin/Data/Managed --generatedcppdir=D:/UnityProject/unity-firebase-realtime-database-master/Temp/StagingArea/Il2Cpp/il2cppOutput 

stdout:
Building libil2cpp.so with AndroidToolChain
	Output directory: D:\UnityProject\unity-firebase-realtime-database-master\Temp\StagingArea\assets\bin\Data\Native\armeabi-v7a
	Cache directory: D:\UnityProject\unity-firebase-realtime-database-master\Library\il2cpp_android_armeabi-v7a\il2cpp_cache
ObjectFiles: 125 of which compiled: 0
Total compilation time: 79 milliseconds.
il2cpp.exe didn't catch exception: Unity.IL2CPP.Building.BuilderFailedException: C:\Program Files\Unity\Hub\Editor\2019.4.10f1\Editor\Data\PlaybackEngines\AndroidPlayer\NDK\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++ @"C:\Users\MSI\AppData\Local\Temp\tmp24D6.tmp" -o "D:\UnityProject\unity-firebase-realtime-database-master\Library\il2cpp_android_armeabi-v7a\il2cpp_cache\linkresult_814CE8AB18E11C9D9399614D11C10624\libil2cpp.so" -shared -Wl,-soname,libil2cpp.so -Wl,--no-undefined -Wl,-z,noexecstack -Wl,--gc-sections -Wl,--build-id -stdlib=libc++ -static-libstdc++ -target armv7-linux-androideabi19 -Wl,--wrap,sigaction -llog -rdynamic -fuse-ld=gold.exe

D:\UnityProject\unity-firebase-realtime-database-master\Temp\StagingArea\Il2Cpp\il2cppOutput/Assembly-CSharp.cpp:18125: error: undefined reference to 'CloseEventSource'
D:\UnityProject\unity-firebase-realtime-database-master\Temp\StagingArea\Il2Cpp\il2cppOutput/Assembly-CSharp.cpp:18110: error: undefined reference to 'CreateEventSource'
D:\UnityProject\unity-firebase-realtime-database-master\Temp\StagingArea\Il2Cpp\il2cppOutput/Assembly-CSharp.cpp:18125: error: undefined reference to 'CloseEventSource'
clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation)


   at Unity.IL2CPP.Building.CppProgramBuilder.PostprocessObjectFiles(HashSet`1 objectFiles, CppToolChainContext toolChainContext)
   at Unity.IL2CPP.Building.CppProgramBuilder.Build(IBuildStatistics& statistics)
   at il2cpp.Program.DoRun(String[] args, List`1 foundAssemblies)
   at il2cpp.Program.Run(String[] args, Boolean setInvariantCulture)
   at il2cpp.Program.Main(String[] args)
stderr:

Unhandled Exception: Unity.IL2CPP.Building.BuilderFailedException: C:\Program Files\Unity\Hub\Editor\2019.4.10f1\Editor\Data\PlaybackEngines\AndroidPlayer\NDK\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++ @"C:\Users\MSI\AppData\Local\Temp\tmp24D6.tmp" -o "D:\UnityProject\unity-firebase-realtime-database-master\Library\il2cpp_android_armeabi-v7a\il2cpp_cache\linkresult_814CE8AB18E11C9D9399614D11C10624\libil2cpp.so" -shared -Wl,-soname,libil2cpp.so -Wl,--no-undefined -Wl,-z,noexecstack -Wl,--gc-sections -Wl,--build-id -stdlib=libc++ -static-libstdc++ -target armv7-linux-androideabi19 -Wl,--wrap,sigaction -llog -rdynamic -fuse-ld=gold.exe

D:\UnityProject\unity-firebase-realtime-database-master\Temp\StagingArea\Il2Cpp\il2cppOutput/Assembly-CSharp.cpp:18125: error: undefined reference to 'CloseEventSource'
D:\UnityProject\unity-firebase-realtime-database-master\Temp\StagingArea\Il2Cpp\il2cppOutput/Assembly-CSharp.cpp:18110: error: undefined reference to 'CreateEventSource'
D:\UnityProject\unity-firebase-realtime-database-master\Temp\StagingArea\Il2Cpp\il2cppOutput/Assembly-CSharp.cpp:18125: error: undefined reference to 'CloseEventSource'
clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation)


   at Unity.IL2CPP.Building.CppProgramBuilder.PostprocessObjectFiles(HashSet`1 objectFiles, CppToolChainContext toolChainContext)
   at Unity.IL2CPP.Building.CppProgramBuilder.Build(IBuildStatistics& statistics)
   at il2cpp.Program.DoRun(String[] args, List`1 foundAssemblies)
   at il2cpp.Program.Run(String[] args, Boolean setInvariantCulture)
   at il2cpp.Program.Main(String[] args)

UnityEngine.Debug:LogError(Object)
UnityEditorInternal.Runner:RunProgram(Program, String, String, String, CompilerOutputParserBase)
UnityEditorInternal.Runner:RunManagedProgram(String, String, String, CompilerOutputParserBase, Action`1)
UnityEditorInternal.IL2CPPBuilder:RunIl2CppWithArguments(List`1, Action`1, String)
UnityEditorInternal.IL2CPPBuilder:ConvertPlayerDlltoCpp(Il2CppBuildPipelineData, String, String, Boolean)
UnityEditorInternal.IL2CPPBuilder:Run()
UnityEditorInternal.IL2CPPUtils:RunIl2Cpp(String, String, IIl2CppPlatformProvider, Action`1, RuntimeClassRegistry)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

Starting a stream results in an error on WebGL build

Starting a stream using:

public void StartStream()
{
        DatabaseReference reference = FirebaseDatabase.Instance.GetReference(COLLECTION_PATH);
        reference.ValueChanged += (sender, e) =>
        {
            Debug.Log(e.Snapshot.GetRawJsonValue());
        };
        reference.DatabaseError += (sender, e) => {
            Debug.Log(e.DatabaseError.Message);
            Debug.Log("Streaming connection closed");
        };
}

Results in a CORS error in the browser when built for the WebGL platform

Error message:

Access to resource at my firebase url from origin 'http://localhost:63620' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

This CORS error does not exist with other API calls such as read, write, push and delete.

UpdateValueAsync documentation

If anyone's having issues using the update functionality, the line showing the method:
reference.UpdateValueAsync ...
should be
reference.UpdateChildAsync ...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.