Add http:// to NSURL if it's not there

后端 未结 5 1187
粉色の甜心
粉色の甜心 2021-01-11 22:50

I am using web view in my app, getting a URL from a text field. It works if the string starts with \"http://\". I am trying to modify the code so that it can also handle the

5条回答
  •  自闭症患者
    2021-01-11 23:16

    NSString *urlString = @"google.com";
    NSURL *webpageUrl;
    
    if ([urlString hasPrefix:@"http://"] || [urlString hasPrefix:@"https://"]) {
        webpageUrl = [NSURL URLWithString:urlString];
    } else {
        webpageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", urlString]];
    }
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:webpageUrl];
    [self.myWebView loadRequest:urlRequest];
    

提交回复
热议问题