我在通过URL请求获取当前URL并将其传递到Web视图上方的文本字段时遇到问题。我尝试记录它并返回NULL,文本字段保持空白。
这是我添加到我的实现文件中的委托:
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSURL* url = [webView.request URL];
_webAddress.text = [url absoluteString];
}
这是我的WebViewController.h文件:
#import <UIKit/UIKit.h>
@interface WebViewController : UIViewController {
IBOutlet UIWebView *_webView;
IBOutlet UITextField *_webAddress;
IBOutlet UIActivityIndicatorView *activityIndicator;
NSTimer *timer;
NSString *_webURL;
}
@property (nonatomic, retain) IBOutlet UIWebView *webView;
@property (nonatomic, retain) IBOutlet UITextField *webAddress;
@property (nonatomic, retain) NSString *webURL;
- (IBAction) doneButton:(id)sender;
@end
这是我的WebViewController.m文件:
#import "WebViewController.h"
@implementation WebViewController
@synthesize webView = _webView;
@synthesize webAddress = _webAddress;
@synthesize webURL = _webURL;
// Dismiss WebViewController
- (IBAction) doneButton:(id)sender {
[[self parentViewController] dismissModalViewControllerAnimated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSURL* url = [webView.request URL];
_webAddress.text = [url absoluteString];
}
- (void)viewDidLoad
{
[_webView addSubview:activityIndicator];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_webURL]]];
timer = [NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) target:self selector:@selector(loading) userInfo:nil repeats:YES];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)loading {
if (!_webView.loading)
[activityIndicator stopAnimating];
else
[activityIndicator startAnimating];
}
- (void)viewDidUnload
{
_webURL = nil;
_webView = nil;
_webAddress = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)dealloc
{
[_webURL release];
[_webView release];
[_webAddress release];
[super dealloc];
}
@end
有人知道我在做错了什么吗?谢谢。
答案 0 :(得分:1)
改为使用- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
代理人。这将为您提供实际的请求。
答案 1 :(得分:0)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL* url = [request URL];
_webAddress.text = [url absoluteString];
}