Search code examples
iosobjective-cuiwebviewtheos

How to make UIWebView go to requested URL


I am building a browser app and I have a UIWebView and a textField I need to know what code I would put in my button to make the URL put in the textField display in the UIWebView

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];   // x is width,y is hght


NSString *urlAddress =     @"http://www.livewiretech.co.nf/Web_app/Home.html";
NSURL *url = [NSURL URLWithString:urlAddress];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];

[self.view addSubview:webView];

I have a textfield

    // Create Text Field
    UITextField *myTextField = [[UITextField alloc]       initWithFrame:CGRectMake(10, 100, 200, 40)];
    [myTextField setBackgroundColor:[UIColor clearColor]];
    [myTextField setText:@"http://Www.url.com"];
    [[self view] addSubview:myTextField];
    [myTextField release];

This is my button

    -(void) goButton {
    //code here
    }

Solution

  • What you can do is create a UITextField and a Go button next to it at the top. Let user input URL in textField and on press of Go button pass the url to UIWebView loadRequest method.

    You need to adjust the UI accordingly to have UITextField at the top and below that UIWebView

    Updated Answer

    Initialise your UIWebView as a property in .h file.

    In your .h file create following properties

    #import <UIKit/UIKit.h>
    
    @interface ViewController : UIViewController {
    
    }
    
    @property (strong, nonatomic) UITextField *urlText;
    @property (strong, nonatomic) UIWebView *webView;
    
    @end
    

    In your .m file

    -(void)viewDidLaod {
        self.urlText = [[UITextField alloc] initWithFrame:CGRectMake(0, 11, 229, 25)];
        self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,40, 300, 500)];    
        UIButton *goButton = [UIButton buttonWithType:UIButtonTypeCustom];
        goButton.frame = CGRectMake(235, 11, 25, 25);
        [goButton setTitle:@"GO" forState:UIControlStateNormal];
        [goButton addTarget:self action:@selector(goButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubView:self.urlText];
        [self.view addSubView:goButton];
        [self.view addSubview:self.webView];
     }
    
    
    
    -(void)goButton:(id)sender {
     NSString *urlAddress = self.urlText.text;
     NSURL *url = [NSURL    URLWithString:urlAddress];   
     NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
     [self.webView loadRequest:request];
    }