2011-06-30 67 views
5

我試圖檢查用戶輸入的URL,但我正在對付一些錯誤和警告。檢查包含「http://」的URL的字符串

-(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
未使用的變量urlAddress響應(兩個)
urlAddress未申報:在URLRequest

有誰知道該怎麼辦?

回答

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]; 
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
if ([[url lowercaseString] hasPrefix:@"http://"]) 
    return url; 
else 
    return [NSString stringWithFormat:@"http://%@", url]; 
0

如果你有一個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; 
}