Unity webview loading webpage locally/by storing cache - unity3d

I am trying to build a unity project, in my project i have to show the web page in app using unity webview either by loading locally or by once storing cache of that web page. i have tried loading locally by downloading a web page but without internet the content of the html files loaded but CSS, JS and Images are not. for loading locally i have pasted the folders and HTML file to a folder in project-> Assests-> Streaming Assets. Image for folders and HTML file is Streaming Assets directory Image the underlined folders and file is used. And in unity editor link for the file is provided like this:- Unity Editor Image and script used to load the file is below
case RuntimePlatform.OSXEditor:
case RuntimePlatform.OSXPlayer:
case RuntimePlatform.IPhonePlayer:
case RuntimePlatform.Android:
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
var src = System.IO.Path.Combine(Application.streamingAssetsPath, Url);
var dst = System.IO.Path.Combine(Application.persistentDataPath, Url);
var result = "";
if (src.Contains("://")) {
var www = new WWW(src);
yield return www;
result = www.text;
} else {
result = System.IO.File.ReadAllText(src);
}
System.IO.File.WriteAllText(dst, result);
webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
}
if (Application.platform != RuntimePlatform.Android) {
webViewObject.EvaluateJS(
"window.addEventListener('load', function() {" +
" 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;" +
" }" +
" }" +
"}, false);");
}
break;
#else
If anyone Knows Please help.

Related

How to properly integrate Google Sign-In into my Unity Android App build

private string text;
void Start()
{
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestIdToken().RequestServerAuthCode(false).Build();
text = "config created";
PlayGamesPlatform.InitializeInstance(config);
text = text + "\n" + "config initialized";
PlayGamesPlatform.Activate();
text = text + "\n" + "activated";
SignInWithPlayGames();
text = text + "\n" + "attempted to sign in";
}
public void SignInWithPlayGames()
{
UnityEngine.Social.localUser.Authenticate((bool success) =>
{
if (success)
{
string authCode = PlayGamesPlatform.Instance.GetServerAuthCode();
text = text + "\n" + "Auth code is: " + authCode;
if (string.IsNullOrEmpty(authCode))
{
text = text + "\n" + "Signed into Play Games Services but failed to get the server auth code.";
return;
}
}
if (!success)
{
text = text + "\n" + "Failed to Sign into Play Games Services.";
return;
}
});
}
When I run this on Unity, I got
config created
config initialized
activate
Failed to Sign into Play Games Services.
attempted to signed in
which is fine since I am using my PC to test it. But I got an interesting result after I run my app on a real device. I got this:
config created
config initialized
activate
attempted to signed in
I think it skip if (success) from public void SignInWithPlayGames() method. My app never shows Google Play UI and I am not sure now if I am using the right code.
I've struggled quite a bit with Google Play in the last few weeks. I did not Retrieve the ID token or auth token in the builder however. It might be causing you problems.
Also, you need to cast the social user into a google user to access its properties.
I got it to work with the following code. (If you do not get it to work with this code, the problem resides in your settings in the googleplay Plugin and/or google play console.)
PlayGamesClientConfiguration config = new
PlayGamesClientConfiguration.Builder()
.Build();
// Enable debugging output (recommended)
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.Activate();
Social.localUser.Authenticate((bool success) =>
{
var googleUser = ((PlayGamesLocalUser)Social.localUser);
if (googleUser.authenticated)
{
// access googleUser properties and store them or use them
}
}

Cannot load scene from asset bundle in standalone

Two scenes I am switching between both are from asset bundles used by this code. The code is working in Editor but not in the build. What I am missing?
public IEnumerator LoadSceneBundle(string assetBundleSceneName, string orignialName) {
//url = "file://" + Application.dataPath + "/AssetBundles/" + assetBundleSceneName + ".unity3d";
Debug.Log(Application.dataPath);
//this code for build
newExtractedPath = Application.dataPath;
//this code for runtime
//newExtractedPath = Application.dataPath.Substring(0, Application.dataPath.Length - 7);
Debug.Log(newExtractedPath +" :: newExtractedPath");
//url = "file://" + Application.dataPath + "/AssetBundles/" + assetBundleSceneName + ".unity3d";
url = "file://" + newExtractedPath + "/AssetBundles/" + assetBundleSceneName + ".unity3d";
Debug.Log("scene load url : " + url);
using (WWW www = WWW.LoadFromCacheOrDownload(url,1)){
yield return www;
if (www.error != null) {
throw new Exception("WWW download had an error : " + url + " " + www.error);
//Debug.Log("");
}
AssetBundle ab = www.assetBundle;
Debug.Log(www.assetBundle.mainAsset);
ab.LoadAll();
Application.LoadLevel(originalName);
ab.Unload(false);
}
}
After deployment, I made an AssetsBundle folder and placed my assetbundle scene files, but it isn't working. All was in vain.
Your path seems wrong. If you are embedding the asset bundles into your game, you should put them under the StreamingAssets folder so they'll end up in the game build. According to the documentation:
Any files placed in a folder called StreamingAssets in a Unity project will be copied verbatim to a particular folder on the target machine.
So do that and use Application.streamingAssetsPath to form your path and you should be able to use WWW.LoadFromCacheOrDownload to get them.
If you want to load an asset bundle for a standalone Unity Application, I think you would be better served by AssetBundle.CreateFromFile() - which is simpler and faster. Only catch is that the asset bundle can't be compressed.
http://docs.unity3d.com/ScriptReference/AssetBundle.CreateFromFile.html

ActionScript 3. Popup Facebook share button on game over

I'm creating flash game for Facebook. For now after Game Over It opens new tab with share button (suggest share user's game score on wall).
It should pop-up window with share button on the same Game window.
For now my code in ActionScript 3 is:
function gameOver(evt:Event)
{
if (!m_iLives){
var req:URLRequest = new URLRequest();
req.url = "http://www.facebook.com/dialog/feed";
var vars:URLVariables = new URLVariables();
vars.app_id = "0000000000000"; // your application's id
vars.link = "https://www.facebook.com/.......";
vars.picture = "http:/pictureN.png";
vars.name = "Name...!";
vars.caption = "Caption";
vars.description = "My score is " + String(score) + " Try and you!";
vars.redirect_uri = "https://www.url.com";
req.data = vars;
req.method = URLRequestMethod.GET;
navigateToURL(req, "_blank");
}
}
For true pop-ups I always use ExternalInterface. The script below will let you create pop-ups. make sure the ExternalInterface is available. And to customize the size of your pop-up replace the with and height variable with your dimensions
ExternalInterface.call("window.open('" + url + "','PopUpWindow','width=" + width + ",height=" + height + ",toolbar=yes,scrollbars=yes')");

Can we load basic javascript function in a webview?

I have implemented a function in webview. I put the javascript function in the html head then load it through web.loadUrl but the webview does not take the function into consideration. Is it possible to load it this way ? or am I on the wrong track ?
"<td><a href='' onclick=\"displaying('image url')\" id=/image"+my_image[i] +"/"+"
class='popup-open'><img
src='"+my_image[i]+"'"+
"width='80' height='65'></a></td></tr><tr>";
the hmtl content
String webData = "<!DOCTYPE html>" +
"<head> "+
"<script>"+"function displaying(url)
{document.getElementById('image').innerHTML =\"<img src=\"url\" width=\"100\" height=\"105\">\";}"+"</script>"
+
" </head><body>"+ html_content +"</tr></table></body></html>";
Maybe is your JavaScript or some syntax shit. First of all, try to figure out what's the error message from WebKit engine.
To display webview's javascript messages, put onConsoleMessage in implementation.
myWebView.setWebChromeClient(new WebChromeClient() {
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d(cm.message() + " -- From line "
+ cm.lineNumber() + " of "
+ cm.sourceId());
return true;
}
});
Make sure you have following enabled
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);

Using PhoneGap to record audio to documents folder on iOS

As part of an iPhone app I'm creating using PhoneGap, I need to be able to use the microphone to record to a new file which is sorted in the apps document folder on the phone.
I think I have the code sorted to actually capture the recording I'm just having trouble creating a blank .wav in the documents folder to record to. According to the PhoneGap API iOS requires that the src file for the audio already exists.
Can anyone help my with the couple of lines of code needed to create this blank file? My code so far is -
function recordAudio() {
var src = "BLANK WAV IN DOCUMENTS FOLDER";
var mediaRec = new Media(src, onSuccess, onError);
// Record audio
mediaRec.startRecord();
// Stop recording after 10 sec
var recTime = 0;
var recInterval = setInterval(function() {
recTime = recTime + 1;
if (recTime >= 10) {
clearInterval(recInterval);
mediaRec.stopRecord();
}
}, 1000);
}
function onSuccess() {
console.log("recordAudio():Audio Success");
}
// onError Callback
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
$('#record-button').
bind('tap', function(){
recordAudio();
})
You may need to create the file first using the File API.
document.addEventListener("deviceready", function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, function fail(){});
}, false);
var gotFS = function (fileSystem) {
fileSystem.root.getFile("blank.wav",
{ create: true, exclusive: false }, //create if it does not exist
function success(entry) {
var src = entry.toURI();
console.log(src); //logs blank.wav's path starting with file://
},
function fail() {}
);
};
tried using something like this?
var src = "blank.wav"; instead of "BLANK WAV IN DOCUMENTS FOLDER" ?