Local function call from UIWebview - iphone

Hi i have an uiwebview, I have prepare the htmlstring format of data to load in webview.
I am using this line to load htmlstring in uiwebview.
[webView loadHTMLString:htmlstring baseURL:[NSURL URLWithString:[NSString stringWithFormat:#"file:/%#//",imagePath]]];
In the html formated string we have an one image button.When i click the image button i want to call one local function in ViewController.m file.
Is it possible ? Please help me .
I am using
<input type=""image"" onclick=""func()"" src=""icon_blog.png"" name=""image"" width=""30"" height=""30"">
<script language=""javascript""> function func(){alert(""hee"");}
But alert not shown in iphone . Any one help me ? Thanks in advance.......

There is no straightforward way to call objective-c code from within page loaded in UIWebView.
The only way is to intercept loading of dummy-pages in UIWebView's delegate (– webView:shouldStartLoadWithRequest:navigationType:). There you can make decisions based on request.URL.
- (BOOL)webView:(UIWebView*)_webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSArray *components = [[[request URL] absoluteString] componentsSeparatedByString:#":"];
if ([components count] > 1 && [[components objectAtIndex:0] isEqualToString:#"objc"]) {
if ([[components objectAtIndex:1] isEqualToString:#"someFunctionality"]) {
// Do something
}
return NO;
}
return YES;
}
You can trigger those requests by clicking a link, submitting a FORM, or from JavaScript by setting the window's location like this: window.location = "objc:someFunctionality";.

Related

Display RSS Feed in iPhone`

I have a list of RSS feeds and I need to display the detail of each feed in iPhone. I got all RSS feeds from the server which I'm displaying in tableview. Now on selecting a row I need to display the discription of RSS Feed which is coming from Server in HTML content like:-
<img border=\"0\" hspace=\"10\" align=\"left\" style=\"margin-top:3px;margin-right:5px;\" src=\"http://timesofindia.indiatimes.com/photo/4881843.cms\" />Cadila Pharmaceutical will seek the govt's nod in two days for initiating clinical trials for a vaccine against swine flu.<img width='1' height='1' src='http://timesofindia.feedsportal.com/c/33039/f/533968/s/1f181b11/mf.gif' border='0'/><div class='mf-viral'><table border='0'><tr><td valign='middle'><img src=\"http://res3.feedsportal.com/images/emailthis2.gif\" border=\"0\" /></td><td valign='middle'><img src=\"http://res3.feedsportal.com/images/bookmark.gif\" border=\"0\" /></td></tr></table></div><br/><br/><img src=\"http://da.feedsportal.com/r/133515347892/u/0/f/533968/c/33039/s/1f181b11/a2.img\" border=\"0\"/><img width=\"1\" height=\"1\" src=\"http://pi.feedsportal.com/r/133515347892/u/0/f/533968/c/33039/s/1f181b11/a2t.img\" border=\"0\"/>
How do I display this HTML Content in our iPhone UI, as this will contain text,hyperlink and images.
Is it proper way to use UIWebview in this case, as UIWebView is heavy weight.
Please read this blog : http://www.raywenderlich.com/2636/how-to-make-a-simple-rss-reader-iphone-app-tutorial,
It is useful for you.
you can do something like below.
first of all
descLbl.text=[self flattenHTML:descLbl.text];//descLbl.text is a text in which you are getting that HTML description...
now in flattenHTML method write like below...
- (NSString *)flattenHTML:(NSString *)html {
NSScanner *thescanner;
NSString *text = nil;
thescanner = [NSScanner scannerWithString:html];
while ([thescanner isAtEnd] == NO) {
[thescanner scanUpToString:#"<" intoString:NULL];
// find end of tag
[thescanner scanUpToString:#">" intoString:&text];
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"\n"] withString:#" "];
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"%#>", text] withString:#" "];
} // while //
return html;
}
let me know it is working or not..
Happy coding!!!!
If you are planning to show HTML entities as it is, i would suggest to go with UIWebView. You can pass this HTML as a string in method loadHTMLString:
If you want the user to view the content as a web page, then loading the url in UIWebView is the best and easiest way.
Like this:
UIWebView *webView = [[UIWebView alloc] init];
NSURL *pageurl = [NSURL URLWithString:http://www.google.com];
NSURLRequest *request = [NSURLRequest requestWithURL:pageurl];
[webView loadRequest:request];
You can simply use RSSKit library.

Best way to have article text with links on iPhone?

I am making an iPhone app that has a bunch of "articles" with certain words that I want to link to other "articles". I need to display the articles in UITableViewCells.
If there is a way to do this without a web view, that's great.
If I need to use a web view, should I just make <a href> style links? How can I have it jump to the article without creating a bunch of actual html pages, just have it let my program know that they clicked on that link and then the program goes and finds the appropriate article from a plist or something?
I've create a test demo using UIWebView and it works fine.
Create two HTML files:home.html and first.html.
// home.html
Home page. first
// first.html
First page. home
//viewDidLoad
self.webView.delegate = self;
NSString *htmlFilePathString = [[NSBundle mainBundle] pathForResource:#"home" ofType:#"html"];
NSURL *htmlFileURL = [[NSURL alloc] initFileURLWithPath:htmlFilePathString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:htmlFileURL];
[self.webView loadRequest:request];
// webView's delegate:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}

How to parse HTML page data in iphone app?

I don't know how to parse HTML page content in iPhone SDK?
I have an iPhone app, in this app I need to show the image and data from the HTML page. I have an HTML page URL, I need to get data from the HTML page URL. Can anyone please guide me to parse HTML content from HTML page and show in iPhone app?
Can you please help me?
EDIT
I have an website in HTML format like this http://www.example.com/mobile/403.html page. I want to develop a native iPhone app for this website. My client wont give the response in XML feed so i need to use this site and parse the HTML contents. This page having many images, live data and tables. Till now i didn't parsed HTML page/content in iPhone SDK. So i need your help to do this? Can you please help me? I hope it is clear comparing with old question. Thanks in advance.
You can add the the image url to the NSMutableArray as code below..
NSMutableArray *array = [[NSMutableArray alloc] init];
NSString *response = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"index1" ofType:#"html"] encoding:NSUTF8StringEncoding error:nil];
// NSLog(#"response == %#", response);
NSString *regexStr = #"<a href=\"([^>]*)\">";
//NSString *regexStr = #"<A HREF=\"([^>]*)\">";
NSError *error;
NSInteger i =0;
// NSInteger length =0;
while (i<[response length]) {
NSRegularExpression *testRegex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
if( testRegex == nil ) NSLog( #"Error making regex: %#", error );
NSTextCheckingResult *result = [testRegex firstMatchInString:response options:0 range:NSMakeRange(i, [response length]-i)];
// NSLog(#"result == %#",result);
NSRange range = [result rangeAtIndex:1];
if (range.location == 0) {
break;
}
NSString * imageUrl = [response substringWithRange:range];
if ([imageUrl hasSuffix:#".jpg"] || [imageUrl hasSuffix:#".gif"] || [imageUrl hasSuffix:#".tiff"] || [imageUrl hasSuffix:#".JPG"] || [imageUrl hasSuffix:#".JPEG"] || [imageUrl hasSuffix:#".png"] || [imageUrl hasSuffix:#".PNG"] || [imageUrl hasSuffix:#".GIF"] || [imageUrl hasSuffix:#".TIFF"]) {
// NSLog(#"%#",imageUrl);
// imageUrl = [imageUrl stringByReplacingOccurrencesOfString:#"/syneye_Portfolio/" withString:#""];
[array addObject:imageUrl];
//[array retain];
}
i= range.location;
//NSLog(#"%i",range.location);
i=i+range.length;
}
You should get the HTML thanks to a networking framework (AFNetworking for instance) and parse it with one of the following options:
custom code
some HTML parsing framework (i don't know any)
loading the HTML in a hidden UIWebView and doing some Javascript inside with stringByEvaluatingJavaScriptFromString:
I still don't understand exactly what you want, but this is what's possible with urls and html pages:
1) The page can be loaded into Safari. Of course a user can do this if the user has the url. But also a native app can launch Safari and supply Safari with the url of the page to load. A native app cannot however launch Safari and give it the actual html page to load, it must the url.
2) A native app can use UIWebView to either a) download and display a html page given a url or: b) If the html exists on the device, then the html page is given to UIWebView then the UIWebView will display it directly.
3) If the intention is to just extract a bit of text or an image or two from the html and then display it,then search for a few postings/tutorials then you can a) load the html page in a hidden UIWebView and use Javascript to access the dom elements or b) if its xhmlt use an xml parser to extract the html tags you are looking for or c) see if there are html parsing frameworks available for html or d) do a hack and string seach for the html tokens in the html directly.
4) Parse the full HTML and display all its contents yourself. Unless this is a very very simple html, without a full set of features and can't handle javascript etc. etc. Do you have a large team and years free in which to write what would effectively be your own browser.
EDIT:
You still keep talking about parsing as if parsing is the same thing as displaying it.
If you just want to display the http page at the url use UIWebView. The UIWebView will parse it AND display it. There's no need for you to parse it yourself. Or launch Safari from you app (but you won't be able to return to your app afterwards).
You say you can't use UIWebView? Why not?
To actually try and parse and display the HTML page yourself would be madness.

loading links in in-app browser in a web view in iphone

I have some local html files in resources.on launch one html,say a.html, is loaded in webview. there are some hyperlinks in that webview(or say the html content) which are links to other html files in my resources.now on click of those links I want to open them in in-app browser.
how to do this.
Any idea????
thnx!!!!
I've not tried this, but it might work!
Create your UIWebView and load the first html file from your bundle
NSString *file = [[NSBundle mainBundle] pathForResource:#"a" ofType:#"html"];
NSString *html = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
[webView loadHTMLString:[NSString stringWithFormat:#"<html><head></head><body>%#</body></html>", html] baseURL:baseURL];
webView.delegate = self;
Then get when the user taps a link
-(BOOL)webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if (inType == UIWebViewNavigationTypeLinkClicked) {
// Find which link is selected, get the file and load it into the UIWebView
}
return YES;
}

Can I format an URL to launch Safari from within my app's UIWebView?

My app has a UIWebView that shows a fair amount of content. For some of that content I would like to exit the app, and launch Safari to handle the web content rather than doing it in my UIWebView. Is there an url format that will explicitly launch Safari rather than loading a page in the UIWebView?
Obviously I can't use http:// since that just opens the url in place. Can I use safari:// or something of the sort?
EDIT: Apologies, I wasn't clear originally. I am looking for a solution that involves changing urls on pages without making modifications to my client. Hoping for a native Safari launching pattern along the lines of tel:// for the phone.
Sure. Then just have the UIWebView delegate do:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString * customScheme = #"safari";
NSURL * loadURL = [request URL]; //this is the url the user tapped
if ([[loadURL scheme] isEqual:customScheme]) {
//if the url starts with "safari://"
NSString * absoluteURL = [loadURL absoluteString];
//replace "safari" with "https"
absoluteURL = [absoluteURL stringByReplacingCharactersInRange:NSMakeRange(0,[customScheme length]) withString:#"https"];
NSURL * openURL = [NSURL URLWithString:absoluteURL];
//open the URL in MobileSafari
[[UIApplication sharedApplication] openURL:openURL];
//tell your UIWebView to ignore this request
return NO;
} else {
//this is not a safari:// url, so handle it normally
return YES;
}
}