1
votes

I am making a simple web browser by using UIWebView. User enters an address on the address bar -> check it.

1.If the text is url -> load the request

2.If the text is string -> perform a google search

In the first case, if string has the format: abc.xyz, how to add a scheme and host to it? Example: user enters google.com -> correct to https://google.com engadget.com -> https://www.engadget.com.

My problem is how to know which part had to add to url(http, https, with or without www).

Update:

use NSURLSeassion to test connect

- (void)checkRequest:(NSString*)urlRequest
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlRequest]];
    [request setHTTPMethod:@"HEAD"];

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
            if (statusCode == 200)
                NSLog(@"Correct url");
            // check status code here
        }
        if (error) {
            // handle other errors here
        }
        // handle data here
    }];
    [task resume];
}

Update 2

Don't need to check url, add http:// scheme and website will automatically redirect to the correct destination.

1

1 Answers

2
votes

in your case i think you need to perform a HEAD request and check the result. For example, with your sample url http://engadget.com. if it response not exists, add www to this url and try again.

NSMutableURLRequest request = [NSMutableURLRequest requestWithURL:inURL];
[request setHTTPMethod:@"HEAD"];
NSURLConnection connection = [NSURLConnection connectionWithRequest:request delegate:self];


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if ([(NSHTTPURLResponse *)response statusCode] == 200) {
        // url exists
    }
}