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];
}
They say:
NSString
may not respond to-rangeWithString
Unused variableurlAddress
in the condition "if … else" (for both)urlAddress
undeclared : in theURLRequest
Does anyone have any idea what to do?
To check if string starts with “http”, use PHP built-in function strpos(). strpos() takes the string and substring as arguments and returns 0, if the string starts with “http”, else not. This kind of check is useful when you want to verify if given string is an URL or not.
Catch Exception from URL() Constructor To check if a string is a URL, pass the string to the URL() constructor. If the string is a valid URL, a new URL object will be created successfully. Otherwise, an error will be thrown.
To check if the current URL contains a string in Javascript, you can apply the “test()” method along with the “window. location. href” property for matching the particular string value with the URL or the “toString(). includes()”, or the “indexOf()” method to return the index of the first value in the specified string.
Use the StartWith() method in C# to check for URL in a String.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With