iPhone - Save URL without setURL:forKey: and NSURL

2019-04-01 17:42发布

问题:

Is there anyway to save a URL with NSUserDefaults without setURL:forKey: that is only available to iOS 4.0 and later?

I am loading HTML files locally with fileURLWithPath, and it starts at an intro page and the user can click through to whatever. For now, everytime a user starts over it loads back default to intro.htm. I would like to be able to save their current page to NSUserDefaults on viewdiddissapear and reload it next time, but can't find any solutions besides setURL:forKey:. Anyone out there know a solution?

回答1:

You can turn the URL into a string:

[[NSUserDefaults standardUserDefaults]
 setObject:[url absoluteString] forKey:@"url"];

And vice versa:

NSURL *url = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults]
                                   objectForKey:@"url"]];