Created NSURL is null

馋奶兔 提交于 2019-12-21 04:25:50

问题


NSURL printing null. What's the reason?

NSString *webStr = [[NSString alloc] initWithFormat:@"%@",[webArray objectAtIndex:1]];

NSLog(@"urlString = %@",webStr); // its printing correct url string

NSURL *webURL = [[NSURL alloc] initWithString:webStr];

NSLog(@"url = %@",webURL); // its printing null

[webURL release];

[webStr release];

回答1:


You should do the following.

NSString *webStr = [[NSString alloc] initWithFormat:@"%@",[webArray objectAtIndex:1]];

NSLog(@"urlString = %@",webStr); // its printing correct url string

NSURL *webURL = [[NSURL alloc] initWithString:[webStr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

NSLog(@"url = %@",webURL); // it should print it

[webURL release];

[webStr release];

I have used NSASCIIStringEncoding but you can use UTF8 too or any other encoding.




回答2:


from the docs for -[NSURL initWithString:]:

If the string was malformed, returns nil.

This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.

which raises: what's your input?




回答3:


NSLog(@"urlString = %@",webStr); // its printing correct url string 

It's not printing the correct URL string. It's just printing the string. So if NSURL *webURL = [[NSURL alloc] initWithString:webStr] returns nil it means that your string is not valid URL.



来源:https://stackoverflow.com/questions/4905843/created-nsurl-is-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!