NSString stringWithContentsOfURL is deprecated. What should I do?

拈花ヽ惹草 提交于 2019-12-06 23:45:50

问题


I've written some code that uses stringWithContentsOfURL, but it turns out that it is now deprecated. Can you help me replace it? Here's my code:

NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
NSArray *listItems = [locationString componentsSeparatedByString:@","];

Additionally, can someone have some sample code to show how it works? What encoding was the original code done in (in my 2 lines above)?

I want to maintain compatibility so what should I choose for the encoding? What does error mean and what is it used for?


回答1:


Use stringWithContentsOfURL:encoding:error:

EDIT: Here's your code using the above method:

NSError *error = nil;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSUTF8StringEncoding error:&error];
NSArray *listItems = [locationString componentsSeparatedByString:@","];

You can change NSUTF8StringEncoding accordingly for whatever data you're importing.




回答2:


The NSString reference says this:

Use stringWithContentsOfURL:encoding:error: or stringWithContentsOfURL:usedEncoding:error: instead.



来源:https://stackoverflow.com/questions/5638909/nsstring-stringwithcontentsofurl-is-deprecated-what-should-i-do

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