Importing a RTF file in a UIWebView (content editable) - ios

I declared my App (a rich text editor) to be able to open any RTF file (coming, for example, from an email attachment). The application delegate sends a "loadContent: (NSURL *) url" message to the UiwebView controller when the user select the attachment. In the receiver, I get the url and load the RTF file in the UIWebView using
- (void) loadContent: (NSURL *) passedURL
{
if (passedURL) {
[self.myWebView loadRequest:[NSURLRequest requestWithURL:passedURL]];
} else {
NSBundle *bundle = [NSBundle mainBundle];
NSURL *indexFileURL = [bundle URLForResource:#"index" withExtension:#"html"];
[self.myWebView loadRequest:[NSURLRequest requestWithURL:indexFileURL]];
}
}
Doing that, everything goes all right, and "myWebView" displays the content of the RTF file. The problem is that this view should be content editable, and the code should contain some javascript that I have in my "index.html" bundled file. I load when starting application. So I added some code to extract the HTML code created from the RTF file to be able later to recreate a complete code, inserting the extracted code in a tag like that:
<div id="content" contenteditable="true"> imported html from rtf should be there</div>
I modified the loadContent method to get that.
- (void) loadContent: (NSURL *) passedURL
{
if (passedURL) {
[self.myWebView loadRequest:[NSURLRequest requestWithURL:passedURL]];
NSString *dum=[self.myWebView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML;"];
NSLog(#"%#",dum);
} else {
NSBundle *bundle = [NSBundle mainBundle];
NSURL *indexFileURL = [bundle URLForResource:#"index" withExtension:#"html"];
[self.myWebView loadRequest:[NSURLRequest requestWithURL:indexFileURL]];
}
}
Looking to the result of the NSLog, I get only the following html
<div id="content" contenteditable="true">Hello folks</div>
Which was the HTML content of myWebView BEFORE I loaded the rtf file...
Do you have any idea of what is going on? Why does dum displays the former code, as the displayed myWebView displays the new one? Is it because the loadRequest is executed in a separated thread and that when executing the next instruction, myWebView still contains the former code?
Thanks
[EDITED] I also tried to NSLog the content of the webView in webViewDidFinishLoad: delegate method, but get the same result: the content of this webView before I opened the RTF attachment file. Is It possible to make a load request in a synchronous way?

This is because loadRequest is asynchronous. You need to wait for the load to finish before trying that NSLog. Take a look at the UIWebViewDelegate docs. Try that NSLog inside/after webViewDidFinishLoad: and you should get better results.

Related

Can i send data into webview?

i have created webview in my app,
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"SimpleCall" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[webview loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];
[self.view addSubview:webview];
now i want to send a data to webview when webview starts load.is there any property for uiwebview?
thanks advance.
you must set the delegate UIWebViewDelegate property on your UIWebView, for example:
webView.delegate = self;
where self conforms to UIWebViewDelegate protocol and implement callback method webViewDidStartLoad (check docs) if you really want to do something when web view starts load. Then, you implement the method:
- (void)webViewDidStartLoad:(UIWebView *)webView {
//you can do something in here, but DON'T call any loaders of webView's - loadHTML or reload, cause this will result in a loop
}
But I doubt that will solve your problem - first of all you probably want to do something when web view finishes. Second - can you elaborate more on what you mean by:
send data to web view
DISCLAIMER: as of iOS 8 and higher you should use WKWebView instead.
EDIT: as clarified in comments you want to update dynamically html contents. In WKWebView docs you can read that there is no option to do that (i.e. dynamically insert options from your NSArray to loaded html string). You have to manually update your html string and then reload WKWebView with new, updated html. Reloading whole html just to update one feature is probably not an option here, so better store the webpage loaded on the server and update dynamically (when web page is updated with new options) by calling:
[webView reload];

UIWebView Source code

I have an IBAction on a button with the following code that I am trying to use to retrieve the source code of a UIWebView:
- (IBAction)loadInAWebView:(id)sender {
[self.webView loadHTMLString:[NSString stringWithFormat:#"Hello: %#", _name.text] baseURL:nil];
NSString *yourHTMLSourceCodeString = [_webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerHTML"];
NSLog(#"%#", yourHTMLSourceCodeString);
}
The use of the code above is from the reference I saw at this link: Getting the HTML source code of a loaded UIWebView.
However, the NSLog function always returns the following:
<head></head><body></body>
This obviously does not reflect the actual source code of the UIWebView that in my mind should be:
<head></head><body>Hello, name</body>
Indeed, the UIWebView returns the "Hello, name" content but the related source code does not.
How can I edit the code above to retrieve the real UIWebView source code?
You need implement UIWebViewDelegate methods - (void)webViewDidFinishLoad:(UIWebView *)webView and set self.webView.delegate = self; Put your code NSString *yourHTMLSourceCodeString = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerHTML"]; to this method

Is it possible to access values of HTML form loaded in UIWebView in iOS

Requirement is to load an HTML form in UIWebView and Access the values filled in that form in Objective-C.
So I was wondering if that's even possible. If so, how?
Thanks.
You can use [UIWebView stringByEvaluatingJavascriptFromString:] method.
use this code..
callJsWithObjectiveC
create JS file demo.js and add code
var hello = function(str){ return str; };
add UIWebView => To embed JavaScript in a dummy html file and load that into the UIWebView
[self.webView loadHTMLString:#"<script src=\"demo.js\"></script>" baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];
Here is the code to make JS call
NString *str=#"hi JavaScript";
NSString *function = [[NSString alloc] initWithFormat: #"hello(%#)", str];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:function];
Now, there is one important safety tip to make this actually work: The UIWebView must actually be loaded a view. It doesn’t have to be visible, but in order for the WebKit engine to execute the JS, it must be on a view.

PreLoad UIWebView on a not yet displayed UIViewController

I have an app where on the very last UIViewController there is a UIWebView... the user navigates through the app and at the very end they can transition (modal) to the final UIViewController with a UIWebView... in it's viewDidLoad I have the UIWebView load the page.
The problem is it takes about 8 seconds to load this page and that annoys users.
How can I load the UIWebView way ahead of time (like when the app is first launched!) if that UIViewController hasn't even been presented yet?
I had your same problem for UIWebView inside a UIPageViewController and I found a better solution.
If you are in FirstViewController and you have your webView in your SecondViewController put the loadHTMLString or loadRequest method in the viewDidLoad of your SecondViewController and call [secondViewController.view layoutSubviews] for start loading in your FirstViewController.
Ex:
FirstViewController
-(void)viewDidLoad{
[super viewDidLoad];
// _secondViewController -> An instance of SecondVieController
[_secondViewController.view layoutSubviews];
}
SecondViewController
-(void)viewDidLoad{
[super viewDidLoad];
NSURL *url =[NSURL URLWithString:#"http://www.google.it"];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
What u can do is, load the html string
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:self.path ofType:#"htm"];
NSError * error;
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:&error];
and when u display the webView load this content in your webView
[self.webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];
then your webview need only render your content and doesn't load the data
/// In Swift 2.0
do{
let path = NSBundle.mainBundle().pathForResource("theName", ofType: "html")!
let html = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(html, baseURL: nil)
}catch{
print("Error is happend")
}
Note: It works the same way for WKWebView
Not sure how much work you want to do for this but I think you could cache/store the data from the URL in something like a NSDictionary, or something similar, using [NSUserDefaults standardUserDefaults] and use that information before actually loading the page.
So, load the first time you use it, after it has been seen then store the data using NSUserDefaults. Next time you go to this page, load from the NSUserDefaults first and call the URL/API in the back ground then update NSUserDefaults with this new data.
If you are requesting or pulling specific information each time, then I don't think this will work. If that is your case, you can probably try loading the data/website in an earlier view controller (probably one that takes the user a while to navigate to) and then send that data to the webview. Something like delegate/protocol or maybe even NSNotificationCenter. Hope this helps.
UIWebView is very tricky object. Simple answer would be: no you can't.
UIWebView won't load a document or an URL if it is not in views hierarchy.
Don't try doing it in different thread/queue either.
What you can do is to add UIWebView to the views hierarchy at the very beginning (as you've mentioned) and then pass it to the last view controller with preloaded data. This may work, but it's not an elegant way.
Side questions is: why does it take 8 secs to load a page? Maybe you can download the content of this page earlier? Is it static or dynamic?

Problems using UIWebView to implement info page

In my app I have a UIWebView-based view controller showing info and credits about the app itself. As part of the info, the app version is displayed, as retrieved from the infoDictionary of the mainBundle. So this string is not in the original HTML; it is set programmatically, by replacing a placeholder.
Therefore the sequence is:
1) I load the HTML into a NSString
2) I replace the placeholder with the actual version
3) I show the resulting string in UIWebView by invoking method loadHTMLString:baseURL:
The HTML also has hyperlinks to some web pages in the internet.
Everything is fine, but for this problem:
If I touch a hyperlink, and therefore navigate to the corresponding web page, I will not be able to go back to my original info page (canGoBack returns NO, goBack does nothing).
Any suggestion?
Thanks in advance.
In the end, I have found a satisfactory solution, that I would like to share.
1) I changed the HTML code of my info page, by inserting the following code where I want to show the app version:
<p>App version:
<script type="text/javascript">
var args = document.location.search.substring(1).split("&");
for (var i in args) {
var nameValue = args[i].split("=");
if (nameValue[0] == "version")
var version = nameValue[1];
}
if (version)
document.write(version);
</script>
</p>
This piece of code will parse the query part of the URL, looking for a "version=<version>" argument, and use its value to show the app version.
2) When preparing the URL to be used by the UIWebView, I retrieve the app version from the main bundle:
NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleVersion"];
Then I append it at the end of my URL string:
NSString* urlString = [NSString stringWithFormat:#"<my_info_page>.html?version=%#", version];
3) Finally, I use the UIWebView to show the page:
NSURL* url = [[NSURL alloc] initWithString:urlString];
NSURLRequest* request [[NSURLRequest alloc] initWithUrl:url];
[mWebView loadRequest:urlRequest];
[urlRequest release];
[url release];
where mWebView is an IBOutlet, of type UIWebView, properly connected to the web view in the XIB file.
It works correctly on my iPhone 4, including the back/forward functions of the web view when following hyperlinks, while keeping the user inside the app.
I would break out of the app and load Safari in this case:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
[[UIApplication sharedApplication] openURL:request.URL];
return NO;
}
The only downside is that the user comes out of your app. You could put an alertview in that method to warn them first...
Alternatively, you'll have to code your own back button.

Resources