检查包含“http://”的网址的字符串 [英] Check string containing URL for "http://"
问题描述
我正在尝试检查用户输入的网址,但我打击一些错误和警告。
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可能不响应-rangeWithString
条件if ... else中未使用的变量urlAddress(对于两者)
urlAddress undeclared:在URLRequest中
NSString may not respond to -rangeWithString
Unused variable urlAddress in the condition "if … else" (for both)
urlAddress undeclared : in the URLRequest
有没有人知道该怎么办?
Does anyone have any idea what to do?
推荐答案
NSString响应 rangeOfString:
,而不是 rangeWithString:
。
NSString responds to rangeOfString:
, not rangeWithString:
.
变量urlAddress在 if
语句和 else
语句中声明。这意味着它只生活在那个范围内。一旦你离开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];
这篇关于检查包含“http://”的网址的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!