我想補充的「http://」只輸入一個簡單的URL我想只需要簡單的URL不包含http://
我曾嘗試
使用戶發現它很容易瀏覽裏面的代碼- (IBAction)uurl:(id)sender {
NSURL *myurl = [NSURL URLWithString : @"http://"];
}
,但它不工作
我想補充的「http://」只輸入一個簡單的URL我想只需要簡單的URL不包含http://
我曾嘗試
使用戶發現它很容易瀏覽裏面的代碼- (IBAction)uurl:(id)sender {
NSURL *myurl = [NSURL URLWithString : @"http://"];
}
,但它不工作
//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];
好的,這是很簡單的事,但我們需要的,如果用戶輸入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
}
它說「預期的標識符或(」我該怎麼辦? –
檢查你的代碼,這已經過測試,並正常工作 – Popeye
使用-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];
未來任何錯誤的解釋嗎? –
不,沒有錯誤...仍然我必須鍵入http:// –
'NSLog myurl'它打印什麼? –