2015-08-07 10 views
6

Sto utilizzando la visualizzazione Web nella mia app, ottenendo un URL da un campo di testo. Funziona se la stringa inizia con "http: //". Sto cercando di modificare il codice in modo che possa gestire anche le situazioni in cui gli utenti non inseriscono "http: //" o "https: //"Aggiungi http: // a NSURL se non è presente

Come verificare se l'URL non ha "http ://" dentro ? Come modificare l'URL per aggiungere "http: //" al suo interno?

NSString *URLString = textField.text; 
NSURL *URL = [NSURL URLWithString:URLString]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
[self.webView loadRequest:request]; 
+0

correlati: [Modifica schema di un NSURL] (http: // StackOverflow. com/q/14393016) –

risposta

9
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]; 
+0

Non c'è alcun motivo per il '= [NSURL nuovo];'. È una memoria sprecata. – rmaddy

0

Prova questo.

NSString *URLString = textField.text; 
if ([URLString rangeOfString:@"http://"].location == NSNotFound && [URLString rangeOfString:@"https://"].location == NSNotFound) 
    { 
     URLString=[NSString stringWithFormat:@"http://%@",textField.text]; 
    }   
    NSURL *URL = [NSURL URLWithString:URLString]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 
[self.webView loadRequest:request]; 
+2

Si consiglia di utilizzare [NSString hasPrefix:] – antonio081014

+1

Sì, perché se http: // è da qualche altra parte nella stringa e non di fronte, non si carica. :) – emotality

0

Permettetemi di aggiornare risposta a Swift 4 e WKWebKit

 var urlString = "www.apple.com" 

    if urlString.hasPrefix("https://") || urlString.hasPrefix("http://"){ 
     let myURL = URL(string: urlString) 
     let myRequest = URLRequest(url: myURL!) 
     webView.load(myRequest) 
    }else { 
     let correctedURL = "http://\(urlString)" 
     let myURL = URL(string: correctedURL) 
     let myRequest = URLRequest(url: myURL!) 
     webView.load(myRequest) 
    } 
0

Try This:

NSString *URL = @"apple.com" ; 
    NSURL *newURL ; 

    if ([URL hasPrefix:@"http://"] || [URL hasPrefix:@"https://"]) { 
     newURL = [NSURL URLWithString:URL] ; 
    } 
    else{ 
     newURL = [NSURL URLWithString:[NSString 
     stringWithFormat:@"http://%@",URL]] ; 
    } 
    NSLog(@"New URL : %@",newURL) ;