Check string containing URL for “http://”

不打扰是莪最后的温柔 提交于 2019-12-04 08:36:42

NSString responds to rangeOfString:, not rangeWithString:.

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.

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.

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

I believe you want the rangeOfString method.

To get rid of your urlAddress warnings you should declare NSURL *urlAddress above if..else:

NSURL *urlAddress = nil;
if (result) {  
    urlAddress = [NSURL URLWithString: textField.text];    
} else {   
    NSString *good = [NSString stringWithFormat:@"http://%@", [textField text]];  
    urlAddress = [NSURL URLWithString: good];     
}   

Use this

NSString *stringUrl = url.absoluteString;

if ([stringUrl localizedCaseInsensitiveContainsString:@"your string"]) {
    //do something
}

It first converts url to string and then checks whether this url contains your string

If you have a NSURL convert it to NSString with

   NSString stringURL = url.absoluteString

Then check whether 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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!