After updating to unity 2021.1.13.f1 isNetworkError and isHttpError is already obselete - unity3d

if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
Does anyone know how to replace this code properly to the updated one

Starting from Unity 2020.2 you now use UnityWebRequest.result
Example from UnityWebRequest.Get
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
switch (webRequest.result)
{
case UnityWebRequest.Result.ConnectionError:
case UnityWebRequest.Result.DataProcessingError:
Debug.LogError(pages[page] + ": Error: " + webRequest.error);
break;
case UnityWebRequest.Result.ProtocolError:
Debug.LogError(pages[page] + ": HTTP Error: " + webRequest.error);
break;
case UnityWebRequest.Result.Success:
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
break;
}
}
Or the simplier example from UnityWebRequest.Post
WWWForm form = new WWWForm();
form.AddField("myField", "myData");
using (UnityWebRequest www = UnityWebRequest.Post("https://www.my-server.com/myform", form))
{
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Form upload complete!");
}
}

I solve mine like that!
instead using: if(www.isNetworkError)
I wrote: if(www.result == UnityWebRequest.Result.ConnectionError)
Full example is below:
IEnumerator Get(string url)
{
using (UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError)
{
Debug.LogError(www.error);
}
}
}

Replace "www.isHttpError" with "(www.result== UnityWebRequest.Result.ProtocolError)" and "www.isNetworkError" with "(www.result == UnityWebRequest.Result.ConnectionError)".
Assuming www means the request object.

Related

LootLocker - How to show local rank

In my game, I am able to show the GlobalRank, however, I would also like to show the position of a player in Ranking according to the global results.
So in the bottom line, there should be the local (on this device) results.
Basically, on the left bottom corner, I want to get the RANK from the LootLocker, but I am struggling to get the rank...
IEnumerator ShowScores()
{
yield return new WaitForSeconds(2);
LootLockerSDKManager.GetScoreList(ID, maxScores, (response) =>
{
if (response.success)
{
LootLockerLeaderboardMember[] scores = response.items;
for (int i = 0; i < scores.Length; i++)
{
playerNames[i].text = (scores[i].member_id +"");
playerScores[i].text = (scores[i].score +"");
playerRank[i].text = (scores[i].rank + "");
//Rank of the localPlayer
Rank.text = (scores["here_Should_Be_This_Player_ID"].rank + "");
LootLockerSDKManager.GetPlayerName
// Entries[i].text = (scores[i].rank + ". " + scores[i].score + ". " + scores[i].member_id);
}
if (scores.Length < maxScores)
{
for (int i = scores.Length; i < maxScores; i++)
{
// Entries[i].text = (i + 1).ToString() + ". none";
}
}
}
else
{
}
});
}
Fixed it with the LootLocker support team
Step 1 - load LootLocker and get the resonse
Step 2 - load the rank and get the resonse2
Step 3 - use the "Response2.rank from the LootLocker
Rank.text = (response2.rank + "");
string playerIdentifier = "PlayerNameRecordOnThisDevice";
LootLockerSDKManager.StartSession(playerIdentifier, (response) =>
{
if (response.success)
{
Debug.Log("session with LootLocker started");
}
else
{
Debug.Log("failed to start sessions" + response.Error);
}
LootLockerSDKManager.GetMemberRank(ID, playerIdentifier, (response2) =>
{
if (response2.statusCode == 200)
{
Debug.Log("GetMemberRank Successful");
}
else
{
Debug.Log("GetMemberRank failed: " + response2.Error);
}
Rank.text = (response2.rank + "");
});
}); ```

when I pushed the phone button to back previous page in Unity webviewScript

using System.Collections;
using UnityEngine;
using System;
using System.Collections.Generic;
public class SampleWebView : MonoBehaviour
{
public string Url;
public GUIText status;
WebViewObject webViewObject;
IEnumerator Start()
{
webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>();
webViewObject.Init(
cb: (msg) =>
{
Debug.Log(string.Format("CallFromJS[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play();
},
err: (msg) =>
{
Debug.Log(string.Format("CallOnError[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play();
},
started: (msg) =>
{
Debug.Log(string.Format("CallOnStarted[{0}]", msg));
},
ld: (msg) =>
{
Debug.Log(string.Format("CallOnLoaded[{0}]", msg));
#if UNITY_EDITOR_OSX || !UNITY_ANDROID
// NOTE: depending on the situation, you might prefer
// the 'iframe' approach.
// cf. https://github.com/gree/unity-webview/issues/189
#if true
webViewObject.EvaluateJS(#"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
window.location = 'unity:' + msg;
}
}
}
");
#else
webViewObject.EvaluateJS(#"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute('src', 'unity:' + msg);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
}
}
");
#endif
#endif
webViewObject.EvaluateJS(#"Unity.call('ua=' + navigator.userAgent)");
},
//ua: "custom user agent string",
enableWKWebView: true);
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
webViewObject.bitmapRefreshCycle = 1;
#endif
webViewObject.SetMargins(10, 140, 10, Screen.height / 360);
webViewObject.SetVisibility(true);
#if !UNITY_WEBPLAYER
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
var exts = new string[]{
".jpg",
".js",
".html" // should be last
};
foreach (var ext in exts) {
var url = Url.Replace(".html", ext);
var src = System.IO.Path.Combine(Application.streamingAssetsPath, url);
var dst = System.IO.Path.Combine(Application.persistentDataPath, url);
byte[] result = null;
if (src.Contains("://")) { // for Android
var www = new WWW(src);
yield return www;
result = www.bytes;
} else {
result = System.IO.File.ReadAllBytes(src);
}
System.IO.File.WriteAllBytes(dst, result);
if (ext == ".html") {
webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
break;
}
}
}
#else
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
}
webViewObject.EvaluateJS(
"parent.$(function() {" +
" window.Unity = {" +
" call:function(msg) {" +
" parent.unityWebView.sendMessage('WebViewObject', msg)" +
" }" +
" };" +
"});");
#endif
yield break;
}
#if !UNITY_WEBPLAYER
//void OnGUI()
//{
// GUI.enabled = webViewObject.CanGoBack();
// if (GUI.Button(new Rect(10, 10, 80, 80), "<")) {
// webViewObject.GoBack();
// }
// GUI.enabled = true;
// GUI.enabled = webViewObject.CanGoForward();
// if (GUI.Button(new Rect(100, 10, 80, 80), ">")) {
// webViewObject.GoForward();
// }
// GUI.enabled = true;
// GUI.TextField(new Rect(200, 10, 300, 80), "" + webViewObject.Progress());
//}
#endif
This is my webview Scirpt for my newspaper App in C#. I need code, when I pushed the phone button to go back previous page in the newspaper.
I tried,
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
However it quits from the app. It does not go back previous page in the newspaper..
Thank you for your help...
if i understand it correctly you should be good if you replace
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
by this:
if(Input.GetKeyDown(KeyCode.Escape))
{
webViewObject.GoBack();
}
According to the example you are using from here https://github.com/gree/unity-webview/blob/master/sample/Assets/Scripts/SampleWebView.cs this is the build in back function. You can see it in the commented out part in your code.

Using Post Request return a multiple values in Unity

I am new to Unity i have created a Post Request from that i want to return the Authentication-Token Header and authorization header and some required json data here is my code
private IEnumerator BasketId()
{
string url = "http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/rest/WFS/inSPIRED-inTRONICS-Site/-/baskets/";
using (UnityWebRequest request = UnityWebRequest.Post(url, "Hello"))
{
yield return request.SendWebRequest();
string token = request.GetResponseHeader("Authentication-token");
if (request.isNetworkError || request.isHttpError)
{
Debug.Log(request.error);
}
else
{
string jsonResut = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data);
obj = JsonConvert.DeserializeObject<BasketId>(jsonResut);
Debug.Log(obj.Uri);
Debug.Log("Authentication-Token: " + token);
yield return obj.Title;
yield return token;
}
}
}
so i could i return the values. Please help me.
Because Coroutine is not immediate (blocking) so you won't be able to return the response directly. What you need to do is to have an event or callback that will be called when your request completed.
Here is how you can achieve it by passing the callback as argument:
private IEnumerator GetBasketId(System.Action<string, BasketId> callback)
{
string url = "http://hololens5.northeurope.cloudapp.azure.com/INTERSHOP/rest/WFS/inSPIRED-inTRONICS-Site/-/baskets/";
using (UnityWebRequest request = UnityWebRequest.Post(url, "Hello"))
{
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.Log(request.error);
if (callback != null)
{
callback(null, null);
}
// callback?.Invoke(null, null); // for short
}
else
{
if (callback != null)
{
string token = request.GetResponseHeader("Authentication-token");
string jsonResut = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data);
obj = JsonConvert.DeserializeObject<BasketId>(jsonResut);
if (callback != null)
{
callback(token, obj);
}
// callback?.Invoke(token, obj); // for short
}
}
}
}
so when you want to start the request simply call something like:
StartCoroutine(GetBasketId((token, basketId) =>
{
if (string.IsNullOrEmpty(token))
{
// Handle error
}
else
{
// Handle success
Debug.Log("Token: " + token);
Debug.Log(basketId.Title);
}
});

Not receive notification with azure notification hub when using tag

I'm new to this. The example of android is from
GetStartedFirebase
Below are the steps:
1) I install the android to my phone
2) I followed this example to create my web api
https//learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-aspnet-backend-gcm-android-push-to-user-google-notification
3) i comment out the AuthenticationTestHandler class
4)i call the below code from fiddle
The DeviceRegistration object
{
"Platform": "gcm",
"Handle": "regid i get from android",
"Tags": [
"1",
"2"
]
}
// This creates or updates a registration (with provided channelURI) at the specified id
public async Task<HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
{
RegistrationDescription registration = null;
switch (deviceUpdate.Platform)
{
case "mpns":
registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
break;
case "wns":
registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
break;
case "apns":
registration = new AppleRegistrationDescription(deviceUpdate.Handle);
break;
case "gcm":
registration = new GcmRegistrationDescription(deviceUpdate.Handle);
break;
default:
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
registration.RegistrationId = id;
var username = "test";
string[] userTag = new string[1];
userTag[0] = "username:" + username;
registration.Tags = new HashSet<string>(userTag);
try
{
await hub.CreateOrUpdateRegistrationAsync(registration);
}
catch (MessagingException e)
{
ReturnGoneIfHubResponseIsGone(e);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
5) Then i call to send the push notification
http://localhost:4486/api/Notifications?pns=gcm&to_tag=test
public async Task<HttpResponseMessage> Post(string pns, [FromBody]string message, string to_tag)
{
var user = "test";
message = "msg";
string[] userTag = new string[1];
userTag[0] = "username:" + to_tag;
Microsoft.Azure.NotificationHubs.NotificationOutcome outcome = null;
HttpStatusCode ret = HttpStatusCode.InternalServerError;
switch (pns.ToLower())
{
case "wns":
// Windows 8.1 / Windows Phone 8.1
var toast = #"<toast><visual><binding template=""ToastText01""><text id=""1"">" +
"From " + user + ": " + message + "</text></binding></visual></toast>";
outcome = await Notifications.Instance.Hub.SendWindowsNativeNotificationAsync(toast, userTag);
break;
case "apns":
// iOS
var alert = "{\"aps\":{\"alert\":\"" + "From " + user + ": " + message + "\"}}";
outcome = await Notifications.Instance.Hub.SendAppleNativeNotificationAsync(alert, userTag);
break;
case "gcm":
// Android
var notif = "{ \"data\" : {\"message\":\"" + "From " + user + ": " + message + "\"}}";
outcome = await Notifications.Instance.Hub.SendGcmNativeNotificationAsync(notif, userTag);
break;
}
if (outcome != null)
{
if (!((outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Abandoned) ||
(outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Unknown)))
{
ret = HttpStatusCode.OK;
}
}
return Request.CreateResponse(ret);
}
No error returned but i do not receive any notification.
I try to remove usertag as below:
outcome = await Notifications.Instance.Hub.SendGcmNativeNotificationAsync(notif);
I am able to receive the notification.
Why the tag doesn't work ?
Any help appreciated.
var allRegistrations = await Notifications.Instance.Hub.GetAllRegistrationsAsync(0);
Check your tag in allRegistrations. If it is there then it should work.
You can check test notification from http://pushtry.com
I'm confused - JSON from Fiddler shows that the registration has "1" and "2" tags, but everywhere in the code you are using "username:test" tag. Can you get this registration from the hub and make sure that it has correct tags?
You can use GetRegistrationAsync<TRegistrationDescription>(String) [1], GetRegistrationsByChannelAsync(String, Int32) [2] or GetAllRegistrationsAsync(Int32) [3] methods to get the registration.
[1] https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.notificationhubclient#Microsoft_Azure_NotificationHubs_NotificationHubClient_GetRegistrationAsync__1_System_String_
[2] https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.notificationhubclient#Microsoft_Azure_NotificationHubs_NotificationHubClient_GetRegistrationsByChannelAsync_System_String_System_Int32_
[3] https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.notificationhubs.notificationhubclient#Microsoft_Azure_NotificationHubs_NotificationHubClient_GetAllRegistrationsAsync_System_Int32_

Unity Facebook : 400 Bad Request

I using following code to get user data from facebook
IEnumerator UserFBDataGet(string accessTkn)
{
var downloader3 = new WWW ( "https://graph.facebook.com/me?fields=id,name,email&access_token="+accessTkn );
//Application.OpenURL ( "https://graph.facebook.com/me?fields=id,name,email&access_token="+accessTkn );
yield return downloader3;
print(" downloader3.text ="+downloader3.text );
if(downloader3.error == null)
{
print(" downloader3.text ="+downloader3.text );
}
else
{
print(" downloader3.error ="+downloader3.error );
}
}
It showing Error
You are trying to load data from a www stream which had the following error when downloading.
400 Bad Request
UnityEngine.WWW:get_text()
c__Iterator1:MoveNext() (at Assets/FBDesktopManager.cs:126)
Even i use WWWForm same error is showing
IEnumerator UserFBDataGet(string accessTkn)
{
userDataGetUrl = "https://graph.facebook.com/me?";
WWWForm wf = new WWWForm();
wf.AddField ("fields","id,name,email") ;
wf.AddField ("access_token",accessTkn) ;
WWW downloader3 = new WWW(userDataGetUrl,wf) ;
yield return downloader3;
print(" downloader3.text ="+downloader3.text );
if(downloader3.error == null)
{
print(" downloader3.text ="+downloader3.text );
}
else
{
print(" downloader3.error ="+downloader3.error );
}
}
But when I call
Application.OpenURL ( "https://graph.facebook.com/me?fields=id,name,email&access_token="+accessTkn );
in that page i get all data properly.
Your url needs to be '%' escaped. Besides unity suggests using WWWForm to pass POST parameters properly.