问题描述
我正在尝试检查用户输入的URL,但是我正在与一些错误和警告进行斗争.
I am trying to check the URL entered by the user, but I am fighting against some errors and warnings.
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
//check "http://"
NSString *check = textField.text;
NSString *searchString = @"http://";
NSRange resultRange = [check rangeWithString:searchString];
BOOL result = resultRange.location != NSNotFound;
if (result) {
NSURL *urlAddress = [NSURL URLWithString: textField.text];
} else {
NSString *good = [NSString stringWithFormat:@"http://%@", [textField text]];
NSURL *urlAddress = [NSURL URLWithString: good];
}
// open url
NSURLRequest *requestObject = [NSURLRequest requestWithURL:urlAddress];
}
他们说:
有人知道该怎么做吗?
推荐答案
NSString响应 rangeOfString:
,而不是 rangeWithString:
.
NSString responds to rangeOfString:
, not rangeWithString:
.
在 if
语句和 else
语句中都声明了变量urlAddress.这意味着它仅存在于该范围内.离开if/else语句后,变量就消失了.
The variable urlAddress is declared both in the if
statement, and in the else
statement. That means it only lives in that scope. Once you leave the if/else statement, the variable is gone.
对于URL,最好以方案开头(例如"http://"),并且您的代码将很高兴接受apple.http://.com为有效.
For a URL it's best if it begins with the scheme (like "http://"), and your code will gladly accept apple.http://.com as being valid.
您可以改为使用 hasPrefix:
方法,如下所示:
You can use the hasPrefix:
method instead, like this:
BOOL result = [[check lowercaseString] hasPrefix:@"http://"];
NSURL *urlAddress = nil;
if (result) {
urlAddress = [NSURL URLWithString: textField.text];
}
else {
NSString *good = [NSString stringWithFormat:@"http://%@", [textField text]];
urlAddress = [NSURL URLWithString: good];
}
NSURLRequest *requestObject = [NSURLRequest requestWithURL:urlAddress];
这篇关于检查包含& quot; http://& quot;的URL的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!