Xamarin iOS load content in UIWebView - c#

I'm trying to make a custom web page and put it in a webview in Xamarin using C#
What I have is a UIViewController containing a UIWebView.
In my project I have a folder like this:
Project
Content
index.html
js
css
But when I try to load the index.html file into the webview nothing happens.
I tried just loading an external webpage and it works fine.
this is my code for loading the content in the ViewDidLoad method of the UIViewController:
string fileName = "Content/index.html";
string localHtmlUrl = Path.Combine(NSBundle.MainBundle.BundlePath, fileName);
MyWebView.LoadRequest(new NSUrlRequest(new NSUrl(localHtmlUrl, false)));
MyWebView.ScalesPageToFit = true;
I think it has something to do with the page not finishing it's loading, but I can't figure out how to do this properly.

Derp, always make sure to set the 'Build Action' on your file to BundleResource on each file to include them in the build by right clicking on them...

Related

Create WebView in Xamarin.iOS

How can I implement a UIwebView for IOS in VisualStudio using Xamarin.IOS and C#?
I can create the webView in the Storyboard but how can I define the URL?
And how can I get the current Url?
Click on the webview after adding a webview in the storyboard, then the Properties will show at the right-bottom of VS like this:
Add the Name as the screenshot shows, press the Enter. Now you can load a URL for the WebView in your .cs file like this:
NSUrl url = NSUrl.FromString("https://www.google.com");
NSUrlRequest urlRequest = NSUrlRequest.FromUrl(url);
webView.LoadRequest(urlRequest);
To get the current url of the webview when it already has loaded a URL via the code:
webView.Request.Url.AbsoluteString;

Load Local CSS File Into Xamarin IOS WebView?

I'm able to load a local HTML file into my WebView like this (this works fine):
var fileName = "Views/Default.html";
var localHtmlUrl = Path.Combine(NSBundle.MainBundle.BundlePath, fileName);
var url = new NSUrl(localHtmlUrl, false);
var request = new NSUrlRequest(url);
WebView.LoadRequest(request);
I'd like to reference a CSS file (also local) in my HTML file:
<link href="Content/style.css" rel="stylesheet">
The CSS file does exist inside of a Content folder, the build action is set to Content for said file.
How can I reference/load the CSS file in question via my html file? Possible?
UPDATE: Had css and html in separate folders. Put them both in a Content folder then updated the hrefs which solved the issue while using LoadRequest.
Check this link
https://developer.xamarin.com/recipes/ios/content_controls/web_view/load_local_content/
Section Additional information
Html generated in code can also be displayed, which is useful for customizing the content. To display an Html string, use the LoadHtmlString method instead of LoadRequest. Passing the path to the Content directory helps the web view resolve relative Urls in the Html, such as links, images, CSS, etc.
// assumes you've placed all your files in a Content folder inside your app
string contentDirectoryPath = Path.Combine (NSBundle.MainBundle.BundlePath, "Content/");
string html = "<html><a href='Home.html'>Click me</a></html>";
webView.LoadHtmlString(html, new NSUrl(contentDirectoryPath, true));

Script is not working in WebView in UWP

I am using following web view in xaml.
<WebView x:Name="FBCommentsTest"></WebView>
And i am trying to embed HTML data to that web view in the following way in the c# end.
FBCommentsTest.NavigateToString("<html><head></head><body><div id=\"fb-root\"></div><div id=\"fb-root\"></div><script>(function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) return;js = d.createElement(s); js.id = id;js.src = \"http://connect.facebook.net/en_US/all.js#xfbml=1&appId=" + APP_KEY + "\";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));</script><div class=\"fb-comments\" data-href=\""
+ mExternalUrl + "\" data-width=\"500\"></div> </body></html>");
But, in the web view i am getting an empty screen not able to get the facebook comments view.
How to enable the script in web view in uwp.
Please help me.
Thanks.
But, in the web view i am getting an empty screen not able to get the facebook comments view. How to enable the script in web view in uwp.
The NavigateToStringmethod does not provide a way to generate or provide css, scripts, images, and fonts resources programmatically. You can refer to WebView.NavigateToString method.
You can transfer your string into HTML file, and use Navigate method to navigate to the HTML page. Just for example, create a HTMLPage file in the project and code for it, then in the c# code behind:
Uri uri = new Uri("ms-appx-web:///HTMLPage1.html");
FBCommentsTest.Navigate(uri);

MVC4 can't find shared layout page

I have an MVC4 web application that i'm adjusting. Currently a controller loads Index.cshtml. In that file i have the following line:
#{
Layout = "~/Views/Shared/_Layout-DoubleColumn.cshtml";
}
So i changed that line to:
#{
Layout = "~/Views/Shared/_Layout-TripleColumn.cshtml";
}
I also copied to _Layout-DoubleColumn.cshtml file and renamed that to _Layout-TripleColumn.cshtml.
Now when i run the application i get the following error message:
The layout page "~/Views/Shared/_Layout-TripleColumn.cshtml" could not
be found at the following path:
"~/Views/Shared/_Layout-TripleColumn.cshtml"
I have no clue what the problem could be, because i'm sure that the file is in the Shared folder...
Anyone any idea what the problem could be?
Make sure the Build Action of the file is set to Content in the properties of the View.

Enable button after writing file to response

There is many similar questions but there is still no clear answer that is solving the problem taking some action after writing some stream to response.
I have a following situation:
On button click I am generating some excel file that I am going to write to response allowing user to download generated file. Imidietly after clicking the button, I am disabling it, to prevent double clicking this button. In Page-Load event handler I have following code:
GenerateBTN.Attributes.Add("onclick", "this.disabled=true;" + ClientScript.GetPostBackEventReference(GenerateBTN, "").ToString());
After Page_Load eventhandler, GenerateBTN_Click handler executes the code needed for generating the file and at the end of this method (handler) I am response writing generated file with following code:
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
Response.WriteFile(#"C:\Reports\" + filename);
Response.End();
The Save As dialog appears and user can download the generated file, but the problem is that the disabled GenerateBTN remains disabled. How to enable it afer Writing generated file to response? I understand that afer clearing current response I can not continue with the initial Response, but is there any way to solve this problem?
You can put an IFrame on the page and set it's visiblity to hidden. Have your button load the file in the IFrame and use Javascript to detect if the IFrame is still loading or not. When the loading is done, enable your button.
Can't supply a code example at the moment, but if you decide to go this route and need a sample, let me know I will update this answer.
Edit for 2nd answer
What you want to do is create a file like "Download.aspx" that you pass in the file name as a querystring parameter. This way, you can have your server get the file from a location outside of the Web Application's path and adjust the header to force a file download.
Download.aspx
using System.IO;
protected void Page_Load(object sender, EventArgs e)
{
string FileName = Server.UrlDecode(Request.Params["FileName"]); //Example: "MyFile.txt"
Response.AppendHeader("Content-Type", "application/force-download");
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.WriteFile(#"C:\MyFolder\" + FileName);
}
You would load the page by calling something like "Download.aspx?FileName=MyFile.txt"
You will need to add checks to make sure the file exists and the querystring parameter exists, but that should force the download and allow you to get the file from another location. When you use an ASPX page to serve the file, you can also do credential checks to see if the user is logged into your site (if you have login logic already) or log the download to a log file/database if you want to keep track of it. It gives you a lot more control over the download process.
As for the IFrame loading code, I'm not 100% sure how this works with a file download, but what I was originally thinking was something like this -- view source on: http://sykari.net/stuff/iframe.
Wrap the button in an UpdatePanel, then simply toggle its enabled property before and after the file work.
You can put an IFrame on the page and
set it's visiblity to hidden. Have
your button load the file in the
IFrame and use Javascript to detect if
the IFrame is still loading or not.
When the loading is done, enable your
button.
Can't supply a code example at the
moment, but if you decide to go this
route and need a sample, let me know I
will update this answer.
I've decided to use your suggestion.. but i still have some questions regarding this problem...
Is it possible to load .txt files in iframe?
Is it possible to load some files that are not included in web application's folder?
The problem with loading txt files in iframe is it does not trigger save as dialog to appear, instead of that file content is displayed inside that iframe.
For loading files into an iframe I've used following code:
HiddenFrame.Attributes["src"] = /GeneratedFiles/ + "test.zip";
You can see that I've had to use relative path and my file has to be included in web app's virtual folder.
What is the best javascript (jquery) eventhandler (function) to detect when Iframe has finished loading? I've used jquery function:
$("#ctl00_ContentPlaceHolder1_HiddenFrame").ready(function () {
if ($("#ctl00_ContentPlaceHolder1_HiddenFrame").attr('src') != '') {
$('#ctl00_ContentPlaceHolder1_GenerateSapFilesBTN').removeAttr("disabled");
}
});
But it appears that button is being enabled before Save As dialog actually appears.. Is it possible to solve this problem with this type of eventHandler or do I have to use some other function...

Categories