-2

I am facing an issue with "NSURL URLWithString" method,

I am expecting to get nil while using the above method if the url string is invalid. But its returning empty value instead.
I have attached the code sample below.

NSString *sampleURLString = @"";
NSURL *sampleURL = [NSURL URLWithString:sampleURLString];

NSLog(@"Sample url string : %@", sampleURLString);
NSLog(@"Sample url : %@", sampleURL);

Additional information:

  • I am using XCode Version 8.1.
  • I have also tested in iOS version (8,9,10) in device and simulator.
  • As of now I have handled this by using "canOpenURL" to check the resulted NSURL and avoided further execution. But I need to know why this issue occurs.
Bharath
  • 2,064
  • 1
  • 14
  • 39

2 Answers2

-1

Objective C

[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Swift

let url = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
Dishant Rajput
  • 1,329
  • 1
  • 10
  • 20
-2

You are assigning an empty string. Check the length of your string to know is it empty or not.

NSString *sampleURLString = @"";
    if (sampleURLString.length <=0) {
        sampleURLString = nil;

    }
    NSURL *sampleURL = [NSURL URLWithString:sampleURLString];

    NSLog(@"Sample url string : %@", sampleURLString);
    NSLog(@"Sample url : %@", sampleURL); 

Output:

Sample url string : (null)

Sample url : (null)

If you want to validate a URL

if (sampleURL && sampleURL.scheme && sampleURL.host) {

    NSLog(@"valid: %@", sampleURLString);

} else{

NSLog(@"Invalid: %@", sampleURLString);
}
Ramesh_T
  • 1,251
  • 8
  • 19