Cocoa Obj-C WebView how to display HTML string - objective-c

I have a string of HTML that was parsed by libxml2.dylib that looks like:
Hello,<br />\n<br />\nThis is almost HTML.<br />\n<br />\n
I've unsuccessfully tried to display certain strings parsed from the XML in a WebView; I'm hoping there's a simple way to do it such as how an HTML page is displayed in my Cocoa application:
HTMLView.h
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
#interface htmlView : NSObject {
IBOutlet WebView * webview;
}
-(IBAction) showHTML:(id) sender;
#end
HTMLView.m
#import "HTMLView.h"
#implementation htmlView
-(IBAction) showHTML:(id) sender
{
[[webview mainFrame] loadRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://www.example.com"]]];
NSString * string = #"<br>test</br>";
[self loadHTMLString:string baseURL:(NSURL *)baseURL];
}
-(void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL {
}
#end

try this... [[aWebView mainFrame] loadHTMLString:aString baseURL:nil];

I've unsuccessfully tried to display certain strings parsed from the XML in a WebView
How did you try to display the strings and what was the problem? I think
-(void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL
Might be what you need...!?
Edit:
You have to call the method on your webview!
What you did now is implementing your own loadHTMLString method in your viewController. Which would be fine if it did anything and did call loadHTMLString on the webview at some point.
[self.webView loadHTMLString....]
I think you have to familiarise yourself a bit more with objective-c.

Related

How to verify that a given time WebView performs JS-code?

This is a Cocoa-component WebView. For example he called JS-function:
[webView stringByEvaluatingJavaScriptFromString:#"foo"];
I need to somehow wait until this function is executed and start doing another job. How this can be done on the Objective-C? I need something like:
[webView waitUntilJavaScriptCodeIsCompleted];
[webView stringByEvaluatingJavaScriptFromString:] is executed synchronously and will return an NSString of the result of executing the passed in script. So, if you just want to know that script has executed, call the function and when it returns, it has executed.
If, however, you're talking about a script with some sort of asynchronous execution, like an XMLHTTPRequest or setTimeout, then you're going to need to have your JavaScript call back into your Objective-C code to let it know when it's finished. Here is an example project that does just that. The most relevant parts are in AppDelegate:
#import "AppDelegate.h"
#import WebKit;
#import JavaScriptCore;
#interface AppDelegate ()
#property (weak) IBOutlet NSWindow *window;
#property (weak) IBOutlet WebView *webView;
#end
#interface AppDelegate (WebDelegate) <WebFrameLoadDelegate>
#end
#implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
JSGlobalContextRef jsGlobalContext = _webView.mainFrame.globalContext;
// Add a function named "allDone" to the window object. It can be called from JavaScript like so:
JSContext* context = [JSContext contextWithJSGlobalContextRef:jsGlobalContext];
context[#"allDone"] = ^{
NSLog(#"All Done was called");
};
context[#"jsLog"] = ^(NSString* message) {
NSLog(#"JSLOG: %#", message);
};
_webView.frameLoadDelegate = self;
NSURL* url = [NSURL URLWithString:#"https://example.com"];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
[_webView.mainFrame loadRequest:req];
}
#end
#implementation AppDelegate (WebDelegate)
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
NSLog(#"Page loaded, calling JavaScript");
// Script that logs a message, and then invokes allDone after 2 seconds.
NSString* script =
#"jsLog('Script running');"
#"setTimeout(function() {\n"
#"jsLog('javascript timer fired, invoking allDone...');\n"
#"window.allDone();\n"
#"}, 2000);";
NSLog(#"Before stringByEvaluatingJavaScriptFromString");
[_webView stringByEvaluatingJavaScriptFromString:script];
NSLog(#"After stringByEvaluatingJavaScriptFromString");
}
#end
Which results in the following output:
Page loaded, calling JavaScript
Before stringByEvaluatingJavaScriptFromString
JSLOG: Script running
After stringByEvaluatingJavaScriptFromString
JSLOG: javascript timer fired, invoking allDone...
All Done was called

Why I get this error? unrecognized selector sent to instance [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
I want highlight text on UIWebView
I'm getting the error "unrecognized selector sent to instance 0x756cef0" when calling -[UIWebView highlightAllOccurencesOfString:]. The selector was declared in WBHighlight.h and I use forward declaration in WBSecondViewController.h.
WBSecondViewController.h
#class WBHighlight;
#import <UIKit/UIKit.h>
#interface WBSecondViewController : UIViewController <UIWebViewDelegate, UIScrollViewDelegate>
#property (weak, nonatomic) IBOutlet WBHighlight *webView;
- (IBAction)searchButtonPressed:(id)sender;
- (IBAction)clearHighlights:(id)sender;
#end
WBSecondViewController.m
#import "WBSecondViewController.h"
#import "WBHighlight.h"
#interface WBSecondViewController ()
#end
#implementation WBSecondViewController
-(IBAction)searchButtonPressed:(id)sender{
NSLog(#"highlighttes");
[_webView highlightAllOccurencesOfString:#"cat"];
}
-(IBAction)clearHighlights:(id)sender{
[_webView removeAllHighlights];
}
WBHighlight.h
#import <UIKit/UIKit.h>
#interface WBHighlight : UIWebView{
}
- (NSInteger)highlightAllOccurencesOfString:(NSString*)str;
- (void)removeAllHighlights;
#end
WBHighlight.m
#import "WBHighlight.h"
- (NSInteger)highlightAllOccurencesOfString:(NSString*)str
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"UIWebViewSearch" ofType:#"js"];
NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[self stringByEvaluatingJavaScriptFromString:jsCode];
NSString *startSearch = [NSString stringWithFormat:#"uiWebview_HighlightAllOccurencesOfString('%#')",str];
[self stringByEvaluatingJavaScriptFromString:startSearch];
NSString *result = [self stringByEvaluatingJavaScriptFromString:#"uiWebview_SearchResultCount"];
return [result integerValue];
}
- (void)removeAllHighlights
{
[self stringByEvaluatingJavaScriptFromString:#"uiWebview_RemoveAllHighlights()"];
}
#end
any idea?
This issue is due to you connected the WBHighlight outlet to a UIWebView.
Probably the WBHighlight is a subclassed UIWebView in which highlightAllOccurencesOfString: method is declared and defined. This method is not present in standard UIWebView, that's why it is throwing an error like: unrecognized selector sent to instance.
You need to change the class of UIWebView to WBHighlight in interface builder.
Go to your identity inspector
Select your WebView
Change the class of UIWebView to WBHighlight
Hekiru, You need to make the object of WBHighlight in order to call that method. And, for this you need to import that class and make object.
Let say,
WBHighlight *objWBHighlight = [WBHighlight new];
//Then, call that required method:
int someVarToAssign = [objWBHighlight highlightAllOccurencesOfString:#"fsfsf"];
Hope, it'll sort-out your problem.Try it.
In any concern let me know. :)

How to access NSArray in another View

I have some problems with my XML parser, written in obj-c.
The parser itself is fine but I cant access the result Array in the DetailView.
I need the values of the array created by the Parser Class in my Master and DetailViewController.
In MasterViewController I do this:
MasterViewController.h
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "TouchXML.h"
#import "Parser.h"
#class Parser;
#interface MasterViewController : UITableViewController{
Parser *theParser;
}
MasterViewController.m
- (void)viewDidLoad
{
theParser = [[Parser alloc] init];
[theParser startParser:xmlPath]; //Now the parser runs and parses all needed values into arrays
}
Then I push on click the DetailView and I want to access the values there too.
UniViewController.h
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "Parser.h"
#interface UniViewController : UITableViewController{
Parser *theParser;
}
UniViewController.m
- (void)viewDidLoad
{
NSLog(#"Name: %#",[[theParser.listArray objectAtIndex: 0]valueForKey:#"name"]);
}
Here I want to access the the Array from the parser but I always get the value (null) ?
In the debugger I saw that theParser has 0x0000 which cant be right...
After I do theParser = [[Parser alloc] init]; here, it has an hex value but I still get the (null).
How can I access the Array values from the DetailView?
Would be really nice if someone could explain me the problem here.
Thanks.
Your detail view has to have a pointer to the array that your MasterView creates (via the parser), try this:
(void)viewDidLoad
{
aParser = [[Parser alloc] init];
[aParser startParser:xmlPath];
myUniView.theParser = aParser; //myUniView is just the detail view you're pushing
and then after this you can push your detail view.

Why is this dynamically generated HTML not being displayed in a UIWebView?

I have HTML I am generating in my app. I know it's valid because I ran it through W3Schools "edit and try it". It performs exactly as I designed it.
Here is the definition of the website in the header file:
#interface ReportViewController : UIViewController <UIWebViewDelegate> {
IBOutlet UIWebView *reportWebView;
}
#property (nonatomic, retain) UIWebView *reportWebView;
#property (nonatomic, retain) NSMutableString *html;
- (void) generateReport;
- (void) Alert: (NSString *) title andData: (NSString *) errorMsg;
#end
Here is where I finish creating the HTML and try to display it:
// now do the table
[html appendString:#"<div><table border class=\"boldtable\">"
"<tr BGCOLOR=\"ADDAFE\">"
"<th>STA </th><th>BS </th><th>HI </th><th>FS </th><th>ELEV </th><th>Desc</th>"
"</tr><p>"];
}
// finally, end the table, etc.
[html appendString:#"</table></div></body></html>"];
// UIWebView *reportWebView = [[UIWebView alloc] init];
//[reportWebView loadHTMLString: html baseURL:nil];
[self.reportWebView loadHTMLString:html baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
}
As you can see, I have tried several different variations of displaying the HTML string. What is the correct way to do this?
Iulius Caesar Jacques Cousteau gave the correct answer in a comment:
reportWebView is an IBOutlet, indicating that it's created in an xib. Is the outlet connected? Is the nib loaded? What's with the commented-out UIWebView *reportWebView = [[UIWebView alloc] init];? Is this your exact code? Are you creating a local variable reportWebView that's shadowing the ivar?
but never came back to set it, therefore I am answering it for him.

Error coming up when trying to implement Google map directions, method definition not found

I have been trying to add a link to Google Maps so that I can show some directions to a location. The only problem i'm having is the code not recognizing the method. Here's samples below, hope they help.
.h:
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#interface More : UIViewController{
}
- (IBAction)directions:(id)sender;
-(CLLocationCoordinate2D)getCurrentLocation;
#end
.m:
- (IBAction)directions:(id)sender {
CLLocationCoordinate2D currentLocation = [self getCurrentLocation];
NSString* address = #"********";
NSString* url = [NSString stringWithFormat: #"http://maps.google.com/maps?saddr=%f,%f&daddr=%#",
currentLocation.latitude, currentLocation.longitude,
[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL: [NSURL URLWithString:url]];
}
Error:
Method definition for 'getCurrentLocation not found
Thanks
It looks like you haven't written getCurrentLocation. I'm not sure what that method is but google for CoreLocationControllerDelegate, that will show you how to get your location.
Is there a reason you don't want to use MKMapView? It really makes your life easy.