G'day,在Objective C/XCode 6中检查用户输入的URL - NSRangeException
我试图在浏览器应用程序中检查用户输入的URL。目的是在用户没有输入时添加http:// etc方案,并且假设他们在Google搜索之后(如果他们在文本字段中包含任何空格)。
我想我只是在那里,但是当我输入一些不是完整的URL而且没有空格的东西时,由于下面的错误而崩溃了。简单地说,
- 输入“国家橄榄球联盟”将正确加载谷歌与搜索词
- 输入“http://www.nrl.com.au”加载网页NRL正确
- 输入“www.nrl.com.au”导致以下错误:
终止应用程序由于未捕获的异常 'NSRangeException',原因: ' - [__ NSCFString replaceCharactersInRange:withString:]:范围或索引超出范围'
我已经看了,没有运气以下类似的问题:
How to validate an(sic) url on the iphone
Checking if a string is a url objective c
这个问题很类似地雷,但没有相当回答:
Correcting user submitted url in xcode objective c
请在下面找到
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
NSString *URLString = textField.text;
NSURL *URL = [NSURL URLWithString:URLString];
if (!URL.scheme) {
NSRange urlSpace = [URLString rangeOfString:@" "];
NSString *urlNoSpace = [URLString stringByReplacingCharactersInRange:urlSpace withString:@"+"];
if (urlSpace.location != NSNotFound) {
// The user typed a space so we assume it's a search engine query
URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@", urlNoSpace]];
} else {
// The user didn't type http: or https: for the scheme
URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", URLString]];
}
}
if (URL) {
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
[self.webview loadRequest:request];
}
return NO;
}
感谢您的帮助,您可以提供,非常感谢我的代码!
谢谢马迪!我不知道'stringByReplacingOccurrencesOfString'。如果我不使用范围,我怎么才能知道用户是否在文本字段中输入了空格? – northsydneybears 2014-10-17 08:22:31
保留所有代码原样。只需更改我在答案中显示的那一行。 – rmaddy 2014-10-17 13:55:09