How to load local HTML file in UIWebView? - iphone

I am newbie to Objective-C.I want to know how to load the local html file(say index.html) into UIWebView,i can able to load the url like this,
-(void)viewWillAppear:(BOOL)animated
{
NSLog(#"willAppear");
UIWebView *myWebView=[[UIWebView alloc]initWithFrame:CGRectMake(20, 20, 400, 400)];
NSURL *url = [[NSURL alloc] initWithString:#"http://www.google.co.in/"];
[myWebView loadRequest:[NSURLRequest requestWithURL:url]];
myWebView.scalesPageToFit = YES;
[self.view addSubview:myWebView];
}
I want to load the local html file instead of loading url.How do i do that?.
and also i want to call the delegate method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType,which is not being called.Any guidance is neatly appreciated.Thanks.

First of all,please go through the apple document before searching in google.I suggest you to go through the basic objective c programming concept.
In reference to UIWebView,i would like to tell you how to load the local html.
UIWebView *myWebView=[[UIWebView alloc]initWithFrame:CGRectMake(20, 20, 400, 400)];
NSString *indexPath = [NSBundle pathForResource:#"index" ofType:#"html" inDirectory:nil];
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:indexPath]]];
[self.view addSubview:myWebView];
To call any delegate methods first implement the UIWebViewDelegate protocol in your class..i.e. in your interface's declaration like below…
#interface YourViewController : UIViewController<UIWebViewDelegate>
Then set your webview delegate to your class..ie.,next after you initialize your web view.
myWebView.delegate = self;
Hope it works…Happy Coding :-)

Related

Press a Button and open a URL in another ViewController

I am trying to learn Xcode by making a simple app.
But I been looking on the net for hours (days) and I cant figure it out how I make a button that open a UIWebView in another ViewController :S
first let me show you some code that I have ready:
I have a few Buttons om my main Storyboard that each are title some country codes like UK, CA and DK.
When I press one of those Buttons I have an IBAction like this:
- (IBAction)ButtonPressed:(UIButton *)sender {
// Google button pressed
NSURL* allURLS;
if([sender.titleLabel.text isEqualToString:#"DK"]) {
// Create URL obj
allURLS = [NSURL URLWithString:#"http://google.dk"];
}else if([sender.titleLabel.text isEqualToString:#"US"])
{
allURLS = [NSURL URLWithString:#"http://google.com"];
}else if([sender.titleLabel.text isEqualToString:#"CA"])
{
allURLS = [NSURL URLWithString:#"http://google.ca"];
}
NSURLRequest* req = [NSURLRequest requestWithURL:allURLS];
[myWebView loadRequest:req];
}
How do I make this open UIWebview on my other Viewcontroller named myWebView?
please help a lost man :D
Well, you've firstViewController already designed and coded, now you've to create secondViewController with a UIWebView binded in IB it self, also it have a setter NSString variable like strUrl that you need to pass at the time of pushing or presenting secondViewController, and assign it to UIWebView in viewDidLoad of secondViewController. See my answer about how to pass a NSString? Also UIWebView has its delegates method (What's delegate & datasource methods? - Apple Doc) Which you can use to handle URL request.
These are the delegate of UIWebView, if you'll going to use it, you need to give UIWebView delegate to self.
- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
firstViewController.m
- (IBAction)ButtonPressed:(UIButton *)sender {
NSURL* allURLS;
//get your URL
secondViewControlelr *secondView=[[secondViewControlelr alloc]init];
second.urlToLoad=allURLS;
[self.navigationController pushViewController:secondView animated:YES];
}
secondViewControlelr.h
//declare url and set property
NSURL *urlToLoad;
secondViewControlelr.m
- (void)viewDidLoad
{
myWebView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];
[self.view addSubview:myWebView];
NSURLRequest *urlReq=[NSURLRequest requestWithURL:self.urlToLoad cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:10];
[myWebView loadRequest:urlReq];
}

reload a UIWebView

I'm using a UIWebView like that in the viewDidLoad:
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 88, 320, 400)]; // init and create the UIWebView
webView.autoresizesSubviews = YES;
webView.userInteractionEnabled = NO;
webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
[webView setDelegate:self];//set the web view delegates for the web view to be itself
NSURLRequest *requestObject = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com"]];//Create a URL object & Set the URL to go to for your UIWebView
[webView loadRequest:requestObject];//load the URL into the web view.
[self.view addSubview:webView];//add the web view to the content view
[webView release], webView = nil;
When I try to change the page, I try that BUT it doesn't working :
[webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.facebook.com"]]];
[webView reload];
The code that's just above is in the action of a TabBar button.
**EDIT :
When I comment
[webView release], webView = nil;
I can see the apple website but not facebook when I push the button! The screen is refreshing in the apple website and not facebook...**
Hundred of thanks to help ;-)
You've released and set your webView to nil. So the object no longer exists. You are calling loadRequest and reload on a nil object which will do nothing.
Assuming you have webView as an instance variable in your class, remove the line
[webView release], webView = nil;
and instead put that in your dealloc method otherwise when you call
[webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.facebook.com"]]];
then you will be calling it on a nil object which will do nothing.
Where did you try this code ?
[webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.facebook.com"]]];
[webView reload];
You already released webview and make it Nil. So it will not work if you did it after it loads www.apple.com.
[webView release], webView = nil;
Remove above two lines once and then try. It should work.
Hope this help.
The potential problem I see is that you are setting the webView value to nil after adding it as subview, but before doing the reload:
[webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.facebook.com"]]];
[webView reload];
here webView is nil... the object still exists (because it is embedded in a view), but the variable does not point to it anymore, so messages are simply ignored.
no need of reload
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
[webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.facebook.com"]]];
}
this may help..!!
Reading your code, I guess that the your webView is declared as #property in the header file. You release this object after the Apple site is loaded. I think that's the reason why it doesn't load the facebook website.
The [webView release]; should be placed within the - (void) dealloc method only.
Please let me know if it works!

Return to app behavior after phone call different in native code than UIWebView

According to Apple's documentation, in order to make phone call from my app, I need to implement the following protocols:
HTML link:
1-408-555-5555
Native application URL string:
tel:1-408-555-5555
However, upon completion of a phone call initiated from an HTML link inside a UIWebView, I am redirected right back to my application. But upon completion of a phone call made from a native application URL string, my iphone stays in the iphone's regular phone application, and if I want to return to my application I have to do so manually.
As far as I can tell from reading what others have said, there is no way to change this behavior.
Here is my question:
Is it true that it's impossible
to return to an application after
making a phone call from a native
application URL string?
Would there be any downside to
implementing a UIWebView instead of
a UILabel in situations where I
really wanted the user to be
redirected back to my application
after completing a phone call?
The simplest way seems to be:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"telprompt:0123456789"]];
You will get a prompt and your app will regain focus after the call is finished.
Behavior does differ between calling -[UIApplication openURL:] with a tel: URL, and clicking a link to the same URL in a UIWebView.
Using a UIWebView instead of a UILabel might have some downsides, but you don't have to actually display the UIWebView to get its tel URL handling behavior. Instead, just load a tel URL request in an instance of UIWebView without adding it to your view hierarchy.
For example:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#interface PhoneCaller : NSObject
{
#private
UIWebView *webview;
}
- (void)callTelURL:(NSURL *)url;
#end
#implementation
- (id)init
{
self = [super init];
if (self)
{
webview = [[UIWebView alloc] init];
}
return self;
}
- (void)callTelURL:(NSURL *)url
{
[webview loadRequest:[NSURLRequest requestWithURL:url]];
}
- (void)dealloc
{
[webview release];
[super dealloc];
}
#end
Allow me to simplify a bit. All you need is this little snippet:
UIWebView *callWebview = [[UIWebView alloc] init];
NSURL *telURL = [NSURL URLWithString:#"tel:number-to-call"];
[callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
which I got here.
*Recently tested successfully on iOS 5.0.
The Eric's Brotto method still works in 5.1. You have to add the webview to the main view before the loadRequest, like this:
NSString *cleanedString = [[phoneNumber componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:#"0123456789-+()"] invertedSet]] componentsJoinedByString:#""];
NSString *escapedPhoneNumber = [cleanedString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *telURL = [NSURL URLWithString:[NSString stringWithFormat:#"tel://%#", escapedPhoneNumber]];
UIWebView *mCallWebview = [[UIWebView alloc] init] ;
[self.view addSubview:mCallWebview];
[mCallWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
(I added a phone number cleaner, to delete any non-number char that blocks this method)

getting HTML source code from webView

I'm making an iphone app...can I get the source from it in objective-c?
Thanks!
Elijah
You can get anything from the web view that JavaScript can return using stringByEvaluatingJavaScriptFromString:. Try something along the lines of
document.lastChild.outerHTML
The document will likely have two child nodes; the first will be the DOCTYPE, and the second the <html> element.
If you need to get the contents of the current URL in your web view you could have something like this in a UIViewController. I didn't compile this code, so there may be some syntax errors, but this should be a solid starting point for your problem.
#interface aViewController : UIViewController <UIWebViewDelegate>
UIWebView *webView;
NSString *htmlSource;
#end
#implementation aViewController
-(void) viewDidLoad {
CGRect webFrame = [[UIScreen mainScreen] applicationFrame];
self.webView = [[UIWebView alloc] initWithFrame:webFrame];
self.webView.delegate = self;
NSURL *aURL = [NSURL URLWithString:#"http://www.myurl.com"];
NSURLRequest *aRequest = [NSURLRequest requestWithURL:aURL];
//load the index.html file into the web view.
[self.webView loadRequest:aRequest];
}
//This is a delegate method that is sent after a web view finishes loading content.
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSLog(#"finished loading");
self.htmlSource = [[NSString alloc] initWithData:[[webView request] HTTPBody] encoding:NSASCIIStringEncoding];
}
#end

Cannot load alternating urls with UIWebview

I have one view holding a list of videos(buttons which can be clicked, each hold a url) which currently bring up a new view which holds the UIWebview, the only problem is I cant pass the url to the webview depending on which button was clicked.
At the moment I just get an empty UIWebview.
How can the url string be passed to the webview so it can load the correct url for each button?
Regards
NSURL *videoURL = [NSURL URLWithString:#"http://..."];
[webView loadRequest:[NSURLRequest requestWithURL:videoURL]];
UPDATE:
In response to comment #3, here's what you can do:
This goes without saying, but keep a reference to the UIWebView instance in Browser
Add an NSString or NSURL #property to Browser
Pass the URL to the Browser instance right after init
In viewDidLoad:, call loadRequest:
So your code might look like this:
- (void)buttonClicked {
Browser *browser = [[Browser alloc] initWithNibName:nil bundle:nil];
browser.URL = [NSURL URLWithString:#"http..."];
[self presentModalViewController:browser animated:YES];
[browser release];
}
and in Browser's viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
[webView loadRequest:[NSURLRequest requestWithURL:URL]];
}