2016-12-23 142 views
-2

返回nil,我面临着“NSURL URLWithString”方法的问题,“NSURL URLWithString”方法不适用于无效URL字符串

我期待得到在使用上述方法,如果该URL字符串无效为零。但它的返回空值。
我附上了下面的代码示例。

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

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

其他信息:

  • 我使用的XCode 8.1版。
  • 我也在iOS版本 (8,9,10)中测试过设备和模拟器。
  • 截至目前,我已经通过使用“canOpenURL”来检查结果NSURL并避免进一步执行。但我需要知道为什么会出现这个问题。
+0

sampleURLString通过你的网址在这里 –

+1

@HimanshuMoradiya:当通过任何URL,如 “http://www.google.com” “URLWithString” 功能是否正常工作,并返回一个有效的NSURL,但只有当我传递如上所示的空url字符串时,我不会像它应该那样得到零。 – Bharath

+0

你在使用webview吗? –

回答

-2

您正在分配一个空字符串。 检查你的字符串的长度,知道它是否为空。

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

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

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

输出:

示例URL串:(空)

示例网址:(空)

If you want to validate a URL 

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

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

} else{ 

NSLog(@"Invalid: %@", sampleURLString); 
} 
-1

目标C

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

斯威夫特

let url = NSURL(string: urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!) 
相关问题