我正在尝试检查用户输入的网址,但我正在对抗一些错误和警告。
-(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
可能无法回复-rangeWithString
条件“if ... else”(对于两者)的未使用变量urlAddress
urlAddress
未声明的:URLRequest
有谁知道该怎么做?
答案 0 :(得分:19)
NSString响应rangeOfString:
,而不是rangeWithString:
。
变量urlAddress在if
语句和else
语句中都被声明。这意味着它只存在于该范围内。离开if / else语句后,变量就消失了。
对于URL,最好是以方案开头(如“http://”),您的代码很乐意接受apple.http://.com为有效。
您可以使用hasPrefix:
方法,如下所示:
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];
答案 1 :(得分:4)
if ( [[url lowercaseString] hasPrefix:@"http://"] )
return url;
else
return [NSString stringWithFormat:@"http://%@", url];
答案 2 :(得分:1)
我相信你想要rangeOfString方法。
答案 3 :(得分:0)
要删除urlAddress
警告,您应在NSURL *urlAddress
上方if..else
声明:
NSURL *urlAddress = nil;
if (result) {
urlAddress = [NSURL URLWithString: textField.text];
} else {
NSString *good = [NSString stringWithFormat:@"http://%@", [textField text]];
urlAddress = [NSURL URLWithString: good];
}
答案 4 :(得分:0)
使用此
NSString *stringUrl = url.absoluteString;
if ([stringUrl localizedCaseInsensitiveContainsString:@"your string"]) {
//do something
}
它首先将url转换为字符串,然后检查此url是否包含您的字符串
答案 5 :(得分:-1)
如果你有一个NSURL用
将它转换为NSString NSString stringURL = url.absoluteString
然后检查此NSString是否包含带有此代码的http://
[stringURL containsString: @"http://"]
- (BOOL)containsString:(NSString *)string {
return [self containsString:string caseSensitive:NO];
}
- (BOOL)containsString:(NSString*)string caseSensitive:(BOOL)caseSensitive {
BOOL contains = NO;
if (![NSString isNilOrEmpty:self] && ![NSString isNilOrEmpty:string]) {
NSRange range;
if (!caseSensitive) {
range = [self rangeOfString:string options:NSCaseInsensitiveSearch];
} else {
range = [self rangeOfString:string];
}
contains = (range.location != NSNotFound);
}
return contains;
}