I have an apps written with Objective C. I can't load web page to UIWebView. UIWebViewDelegate not working. My app code ;
#import <UIKit/UIKit.h>
#interface Reklamlarim : UIView <UIWebViewDelegate>
- (void)webSayfasiYukle;
#end
I did it this way .m page. webViewDidFinishLoad and webView didFailLoadWithError: not working.
#import "Reklamlarim.h"
#implementation Reklamlarim
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self webSayfasiYukle];
}
return self;
}
- (void)webSayfasiYukle{
NSLog(#"webSayfasiYukle");
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
webView.delegate = self;
NSString *url=#"http://www.google.com";
NSURL *nsurl=[NSURL URLWithString:url];
NSURLRequest *nsrequest=[NSURLRequest requestWithURL:nsurl];
[webView loadRequest:nsrequest];
[self addSubview:webView];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(#"webViewDidFinishLoad");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"webView didFailLoadWithError");
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)aRequest navigationType:(UIWebViewNavigationType)navigationType {
return YES;
}
I have, ios 8 device, xcode 6.3. I'm sorry for my bad english.
thanks ...
You need to check how you are initiating the Reklamlarim view because
- (id)initWithFrame:(CGRect)frame
is only calling when you are initiating from some where and call this init function it doesn't call automatically.. so move [self webSayfasiYukle]; to
-(void)awakeFromNib {
[self webSayfasiYukle];
}
like this and try.
Related
I have this file that I'm trying to reload but when I reload it I get the screen that is supposed to show up and then a blank screen until I hit reload again. I'm not sure why I'm getting this blank screen. Also, I do not get anything from
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {}
nor
-(void)didReceiveMemoryWarning
Here's my viewController.m file I have the index.html file in the same directory as it does load once but I'm not sure if webkit is crashing or where
#import "ViewController.h"
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
#interface ViewController ()
#end
#implementation ViewController
NSString *localURL;
NSURLRequest *urlRequest;
- (void)viewDidLoad {
[super viewDidLoad];
JSContext *ctx = [[JSContext alloc] init];
ctx[#"console"][#"log"] = ^(NSString *message) {
NSLog(#"Javascript log: %#", message);
};
// Do any additional setup after loading the view, typically from a nib.
// [UIView setAnimationsEnabled:NO];
//_webView = [[WKWebView alloc] initWithFrame:self.view.frame];
// _webView.navigationDelegate = self.webView ;
// _webView.UIDelegate = self;
//[self.view addSubview:_webView ];
_webView= [[WKWebView alloc] initWithFrame:CGRectMake(0, 100, 500, 500)];
localURL = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
urlRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:localURL]];
[_webView loadRequest:urlRequest];
[self.view addSubview:_webView];
//button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:#selector(reload) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Reload" forState:UIControlStateNormal];
button.frame = CGRectMake(10.0, 20.0, 100.0, 50.0);
button.backgroundColor = UIColor.blackColor;
[self.view addSubview:button];
}
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
// Reload current page, since we have crashed the WebContent process
// (most likely due to memory pressure)
NSLog(#"most likely due to memory pressure reloaded");
[webView reload];
}
-(void)reload{
NSLog(#"reloading now");
[self.webView loadRequest:urlRequest];
//[self.webView stopLoading];
// [self loadView];
//[_webView loadRequest:urlRequest];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
NSLog(#"memory issue");
}
//- (IBAction)rButton:(UIButton *)sender {
// NSLog(#"Well we didnt crash");
// [self.webView reload];
//}
#end
If the problem is due to a termination of the web the delegate function webViewWebContentProcessDidTerminate will be called.
In your case it looks that you didn't set the viewController as the navigationDelegate of the webview:
webview.navigationDelegate = self
I need help. I have two button, and I need each button to open a different web page in my UIWebView (for example: button1 open website apple.com, button2 open google.com). I can not find any tutorial that would help me. Thx for help (I use Storyboard).
There is my code, but something is wrong, because I see only a black screen (after click on the button)
TabulkaViewController.m
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(10, 240, 300, 35);
[myButton setTitle:#"Buttonone" forState:UIControlStateNormal];
[myButton addTarget:self action:#selector(myButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview: myButton];
}
-(void) myButtonClick:(NSString *)myString
{
NSURL *url = [NSURL URLWithString:#"http://www.apple.com/"];
WebViewController *viewWeb = [[WebViewController alloc] initWithURL:url andTitle:#"Apple"];
[self presentViewController:viewWeb animated:YES completion:nil];
}
WebViewController.h
#import <UIKit/UIKit.h>
#interface WebViewController : UIViewController <UIWebViewDelegate>
{
NSURL *theURL;
NSString *theTitle;
IBOutlet UINavigationItem *webTitle;
}
- (id)initWithURL:(NSURL *)url;
- (id)initWithURL:(NSURL *)url andTitle:(NSString *)string;
#property (strong, nonatomic) IBOutlet UIWebView *viewWeb;
#end
WebViewController.m
#import "WebViewController.h"
#implementation WebViewController
- (void)viewDidLoad
{
[super viewDidLoad];
webTitle.title = theTitle;
NSURLRequest *requestObject = [NSURLRequest requestWithURL:theURL];
[_viewWeb loadRequest:requestObject];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (id)initWithURL:(NSURL *)url andTitle:(NSString *)string {
if( self = [super init] ) {
theURL = url;
theTitle = string;
}
return self;
}
-(id)initWithURL:(NSURL *)url {
return [self initWithURL:url andTitle:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
_viewWeb.delegate = nil;
[_viewWeb stopLoading];
}
#end
When working with storyboard, it would help if you upload your project file somewhere.
But from experience you need to set your webView delegate to your class WebViewController
you can do it by adding this in your viewDidLoad:
self.webView.delegate = self;
then you must implement the shouldStartLoadWithRequest delegate call, this is a good start.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
return YES;
}
let me know if this fixes it.
EDIT:
after checking your project, change WebViewController->viewDidLoad to this:
- (void)viewDidLoad
{
[super viewDidLoad];
// init webview
_viewWeb = [[UIWebView alloc] initWithFrame:self.view.frame];
_viewWeb.delegate = self;
// add it to this controller's view
[self.view addSubview:_viewWeb];
webTitle.title = theTitle;
NSURLRequest *requestObject = [NSURLRequest requestWithURL:theURL];
[self.viewWeb loadRequest:requestObject];
}
your _viewWeb wasn't initialized as I suspected, See my comments on how to initialize it and how to add it to your WebViewController
EDIT2:
Added constraints in for the web view to take full screen, I recommend you read-up about auto layout in apple docs
- (void)viewDidLoad
{
[super viewDidLoad];
// init webview
_viewWeb = [[UIWebView alloc] initWithFrame:self.view.frame];
_viewWeb.delegate = self;
// add it to this controller's view
[self.view addSubview:_viewWeb];
// add constraints
NSDictionary* dict = #{#"viewWeb":_viewWeb};
_viewWeb.translatesAutoresizingMaskIntoConstraints = NO;
NSArray* constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[viewWeb]-0-|" options:0 metrics:nil views:dict];
[self.view addConstraints:constraints];
constraints = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[viewWeb]-0-|" options:0 metrics:nil views:dict];
[self.view addConstraints:constraints];
webTitle.title = theTitle;
NSURLRequest *requestObject = [NSURLRequest requestWithURL:theURL];
[self.viewWeb loadRequest:requestObject];
}
I've researched and researched and still don't understand why shouldStartLoadWithRequest is never called. My page loads fine and some of the UIWebview delegate protocol methods are called. Please find relevant snippets from my code below:
Synthesize my webview in my .m (defined in a header file):
#implementation PortViewController
#synthesize WebView = myWebView;
I load my webview successfully:
myURLString = [NSString stringWithFormat:#"https://%#", defaultWebsite];
myURL = [NSURL URLWithString: myURLString];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myURL];
[myWebView loadRequest:myRequest];
set my delegate to self
- (void)viewDidLoad
{
[super viewDidLoad];
[myWebView setOpaque:NO];
[myWebView setBackgroundColor:[UIColor clearColor]];
//myWebView.description.
myWebView.delegate = self;
}
all of my protocol methods are called EXCEPT shouldStartLoadWithRequest
- (void)webViewDidStartLoad:(UIWebView *)myWebView {
[activityIndicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)myWebView {
[activityIndicator stopAnimating];
}
- (BOOL)WebView:(UIWebView *)myWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(#"inside Webview");
if([[request.URL absoluteString] hasPrefix:#"http://www.nzx"]) {
// do stuff
NSLog(#"Have caught the prefix");
return YES;
}
return NO;
}
Thanks in advance.
Try setting the delegate in ViewWillAppear instead of ViewDidLoad
-(void)viewWillAppear:(BOOL)animated
{
myWebView.delegate = self;
}
and include the webview delegate in your interface of PortViewController.m file
#interface PortViewController ()<UIWebViewDelegate>
#end
It should work.
delegate method should be:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
And if you have UIWebView in xib, then probably you are trying to load request when UIWebView is nil
So make sure your myWebView instance exists.
I have an app where I would like to push a button and have the user taken to a web view. However, I would like a particular page to load depending on the button that's pushed. Originally I thought about creating a separate web view for each button, but that only caused more issues, which I won't go into. So my question is: How can I load different URL's into a web view, based on whether a particular button is pushed?
I thought about using the prepareForSegue method, but thought that might be over complicating things. Any direction would be great.
so you must create new viewController with UIWebView inside it.
On newViewController create a NSString property named url or somethings like that
example:
#property (retain, nonatomic) NSString *url;
#property (weak, nonatomic) IBOutlet UIWebView *webView;
On buttonTouchUpInside event in oldViewController
UIStoryboard *mainStorybroad = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
newViewController *webViewController = [mainStorybroad instantiateViewControllerWithIdentifier:#"webviewIdentifier"];
webViewController.url = #"url string";
and final, in newViewController you just do:
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
Why don't you link the button in IB to just do a modal transition to the view controller page? Then, in the viewdidload on the new view controller, the code should look something like this:
NSString *fullURL = #"google.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_webView loadRequest:requestObj];
How many buttons do you have? If it's just a couple, then I would just create an extra couple view controllers. If it's a bunch, you could always create a global variable (I can already hear the cringing...) and set the variable equal to the desired URL depending on which button was pushed.
How can I load different URL's into a web view, based on whether a particular button is pushed?
There are two basic approaches to recognizing different buttons:
separate actions: You can create a separate action method for each button, and then just hook up each button to the corresponding action.
single action: You can create a single action for all the buttons, and use some property of the buttons to differentiate between them.
The first one looks like this:
- (IBAction)button1Action:(UIButton*)sender
{
[self.webView loadRequest:[NSURLRequest requestWithURL:url1]];
}
- (IBAction)button2Action:(UIButton*)sender
{
[self.webView loadRequest:[NSURLRequest requestWithURL:url2]];
}
The second looks like:
- (IBAction)buttonsAction:(UIButton*)sender
{
switch (sender.tag) {
case button1Tag:
[self.webView loadRequest:[NSURLRequest requestWithURL:url1]];
break;
case button2Tag:
[self.webView loadRequest:[NSURLRequest requestWithURL:url2]];
break;
}
}
Here is the code for .h and .m File
Create a XIB and Put UIWebView on it and bind it to the class.
For Header File
#import <UIKit/UIKit.h>
#interface NewWebViewController : UIViewController<UIWebViewDelegate> {
IBOutlet UIWebView *webView;
NSString *currentURL;
UIActivityIndicatorView *activityView;
}
#property (nonatomic, copy) NSString *currentURL;
#property (nonatomic, retain) UIActivityIndicatorView *activityView;
#end
For Implementation File (.m)
#import "NewWebViewController.h"
#interface NewWebViewController ()
#end
#implementation NewWebViewController
#synthesize currentURL;
#synthesize activityView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
webView.frame = self.view.frame;
[webView setScalesPageToFit:YES];
NSURL *url = [NSURL URLWithString:self.currentURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
self.activityView = [[[UIActivityIndicatorView alloc] init] autorelease];
self.activityView.tag = 1;
self.activityView.hidesWhenStopped = YES;
UIView *customView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)] autorelease];
self.activityView.center = customView.center;
[customView addSubview:self.activityView];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:customView] autorelease];
[self.activityView startAnimating];
}
#pragma mark UIWebView Delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
[self.activityView startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[self.activityView stopAnimating];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"Error %#",[error description]);
[self.activityView stopAnimating];
}
- (void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
[webView stopLoading];
webView.delegate = nil;
webView = nil;
self.activityView = nil;
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
webView.frame = self.view.frame;
return YES;//(interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void) dealloc {
[currentURL release];
[webView release];
[super dealloc];
}
#end
Here how to use this
- (void) openWebViewControllerWithURL:(NSString*) url {
if (!url) {
return;
}
NewWebViewController *vController = [[NewWebViewController alloc] initWithNibName:#"NewWebViewController" bundle:nil];
vController.currentURL = url;
[self.navigationController pushViewController:vController animated:YES];
[vController release];
}
On click of button just pass the URL you want to load
like this
[self openWebViewControllerWithURL:#"http://www.google.com"];
I want to add activity indicator to a web view.
But i don't know when web view finish loading.
I start animating in viewdidload..
You shouldn't start animating in viewDidLoad. Conform to the
UIWebViewDelegate
protocol and make your web view's delegate your view controller, then use the delegate methods:
#interface MyVC: UIViewController <UIWebViewDelegate> {
UIWebView *webView;
UIActivityIndicatorView *activityIndicator;
}
#end
#implementation MyVC
- (id)init
{
self = [super init];
// ...
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
activityIndicator.frame = CGRectMake(x, y, w, h);
[self.view addSubview:activityIndicator];
webView = [[UIWebView alloc] initWithFrame:CGRectMake(x, y, w, h)];
webView.delegate = self;
// ...
return self;
}
- (BOOL)webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)rq
{
[activityIndicator startAnimating];
return YES;
}
- (void)webViewDidFinishLoading:(UIWebView *)wv
{
[activityIndicator stopAnimating];
}
- (void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error
{
[activityIndicator stopAnimating];
}
#end
Implement the UIWebViewDelegate protocol
These are the delegates you need to implement in your code:
- (void)webViewDidStartLoad:(UIWebView *)webView; //a web view starts loading
- (void)webViewDidFinishLoad:(UIWebView *)webView;//web view finishes loading
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error; //web view failed to load
You will want to listen for the web view delegate callbacks to correctly show your activity indicator.
Specifically you will want to listen for:
webViewDidStartLoad: (start your activity indicator animation)
webViewDidFinishLoad: (end it)
webView:didFailLoadWithError: (end it)
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebViewDelegate_Protocol/Reference/Reference.html
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.webViewRef.delegate = self;
NSURL *websiteUrl = [NSURL URLWithString:Constants.API_TERMS_AND_CONDITIONS_URL];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:websiteUrl];
[self.webViewRef loadRequest:urlRequest];
}
#pragma mark
#pragma mark -- UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
[self.activityIndicator startAnimating];
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
[self.activityIndicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[self.activityIndicator stopAnimating];
self.activityIndicator.hidden = YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
[self.activityIndicator stopAnimating];
self.activityIndicator.hidden = YES;
}