Question

I have an application at the moment that basically opens a url depending on what the user has typed into a textbox. The logic for this is as such:

Predetermined beginning + User Input + Predetermined End

So basically my URL is 3 concatenated strings. Now I know the link is being formed properly (I've put the same snip of code into a label) but nothing happens when I press the button to load the webview.

It works perfectly fine when I use the below, where I explicitly type https://google.com

- (IBAction)btnSearchPress:(id)sender {
    [self.view endEditing:YES];
    [super viewDidLoad];
    NSString *fullURL  = @"https://google.com";
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [_wbView loadRequest:requestObj];
}

However nothing happens when I use this code which includes my concatenated url:

- (IBAction)btnSearchPress:(id)sender {
    [self.view endEditing:YES];
    [super viewDidLoad];
    NSString *fullURL  = [NSString stringWithFormat:@"%@%@%@", _urlPrefix.text,_txtInput.text, _urlSuffix.text];
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [_wbView loadRequest:requestObj];
}

Any help would be much appreciated.

UPDATE: I'm fairly sure having the stringWithFormat is causing this problem just unsure how to get around it.:

Was it helpful?

Solution

Check if fullURL starts with http:// or https://, if not prefix that.

- (IBAction)btnSearchPress:(id)sender {
    [self.view endEditing:YES];
    [super viewDidLoad];
    NSString *fullURL  = [NSString stringWithFormat:@"%@%@%@", _urlPrefix.text,_txtInput.text, _urlSuffix.text];

    if ( ! ([fullURL hasPrefix:@"http://"] || [ fullURL hasPrefix:@"https://"]) ) {
     fullURL = [NSString stringWithFormat:@"http://%@", fullURL ];
    }

    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [_wbView loadRequest:requestObj];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top