2014-02-11 65 views
0

我想補充的「http://」只輸入一個簡單的URL我想只需要簡單的URL不包含http://

我曾嘗試

使用戶發現它很容易瀏覽裏面的代碼
- (IBAction)uurl:(id)sender { 
    NSURL *myurl = [NSURL URLWithString : @"http://"]; 
} 

,但它不工作

+0

未來任何錯誤的解釋嗎? –

+0

不,沒有錯誤...仍然我必須鍵入http:// –

+0

'NSLog myurl'它打印什麼? –

回答

0
//This is what the user types, depending on the type of input you use 
NSString *urlString = @"www.bla.com"; 

NSString *httpString = @"http://"; 
urlString = [httpString stringByAppendingString:urlString]; 

//OR urlString = [NSString stringWithFormat:@"http://%@",urlString]; 

NSURL *url = [NSURL URLWithString:urlString]; 
0

好的,這是很簡單的事,但我們需要的,如果用戶輸入http://https://自己檢查爲好。所以,請參見下面在評論

- (IBAction)uurl:(id)sender 
{ 
    // Our to NSStrings that we want to be checking for. 
    static NSString *httpsStr = @"https://"; 
    static NSString *httpStr = @"http://"; 

    NSString *urlStr = @"www.google.com"; // User input however you take this 

    // Our check to make sure that the urlStr passed in does already have http or https 
    if(![urlStr hasPrefix:httpsStr] && ![urlStr hasPrefix:httpStr]) { 
     // If it doesn't have anything our default HTTP Protocol will be http 
     urlStr = [NSString stringWithFormat:@"http://%@", urlStr]; 
    } 

    // If the user has entered the http or https themselves ignore reseting to http 
    // Set our urlStr as the URL we want to use. 
    NSURL *url = [NSURL URLWithString:urlStr]; 

    // At this point you would do whatever it is you want to do with the url 
} 
+0

它說「預期的標識符或(」我該怎麼辦? –

+0

檢查你的代碼,這已經過測試,並正常工作 – Popeye

0

使用-initWithScheme:host:path:

// your user input string 
NSString *userString = @"www.apple.com"; 

NSURL *yourURL; 

if (![userString hasPrefix:@"http://"]) 
    yourURL = [[NSURL alloc] initWithScheme:@"http" host:userString path:@"/"]; 
else 
    yourURL = [[NSURL alloc] initWithString:userString]; 
+0

我全力以赴使用'initWithScheme:主機:路徑:'但你的代碼如何處理情況當我通過'http:// www.apple.com'? – Popeye

+0

@Popeye你在你自己的回答中回答了這個問題,使用'hasPrefix:'來檢查方案是否已經存在於用戶字符串中。如何正確使用'-initWithScheme:host:path:' – Emmanuel

+0

我不是在談論我的代碼,忽略我的代碼行爲,因爲它不存在。我試圖幫助改進你的答案,但如果你不我只是不同意你的答案,因爲它可能會導致更多的問題-1請注意我在downvote之前給了機會改進。 – Popeye

相關問題