Check the line containing the url for "http: //"

I am trying to verify the URL entered by the user, but I am struggling with 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];
}

They say:

NSStringmay not respond to an -rangeWithString
unused variable urlAddressin the condition "if ... else" (for both)
urlAddressuneclared: inURLRequest

Does anyone know what to do?

+5
source share
5 answers

NSString responds to rangeOfString:, not 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];
+19
if ( [[url lowercaseString] hasPrefix:@"http://"] )
    return url;
else
    return [NSString stringWithFormat:@"http://%@", url];
+4
+1

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];     
}   
0

NSURL, NSString

   NSString stringURL = url.absoluteString

Then check if this NSString contains http: // with this code

 [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;
}
0
source

All Articles