天,
我正在尝试在浏览器应用程序中检查用户输入的 URL。目的是在用户没有输入 http:// 等方案时添加它,并且如果他们在文本字段中包含任何空格,则假定他们在谷歌搜索之后。
我想我就快到了,但是每当我输入不是完整的 URL 并且没有空格的内容时,就会由于以下错误而崩溃。简单地说,
- 输入“National Rugby League”将使用该搜索词正确加载 Google
- 输入“ http://www.nrl.com.au ”正确加载 NRL 网页
- 输入“www.nrl.com.au”会导致以下错误:
由于未捕获的异常“NSRangeException”而终止应用程序,原因:“-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds”
我查看了以下类似的问题,但没有运气:
这个问题与我的非常相似,但没有完全回答:
请在下面找到我的代码
- (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;
}
感谢您提供的任何帮助,非常感谢!