我尝试在xCode中编程,但这对我来说是新的。我需要为ios 5编写简单的webview应用程序。我的应用程序必须加载每次打开时在设置中定义的URL。我创建了xCode项目并将settings.bundle添加到它:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>PreferenceSpecifiers</key>
<array>
<dict>
<key>DefaultValue</key>
<string>http://192.168.0.4/portal.aspx</string>
<key>Key</key>
<string>serverName</string>
<key>KeyboardType</key>
<string>Alphabet</string>
<key>Title</key>
<string>Server</string>
<key>Type</key>
<string>PSTextFieldSpecifier</string>
</dict>
</array>
<key>StringsTable</key>
<string>Root</string>
</dict>
</plist>
我的代码:
(void)viewDidLoad
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
server = [defaults objectForKey:@"serverName"];
if(server==nil)
server=@"http://google.com";
[super viewDidLoad];
[proView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: server]]];
proView.scalesPageToFit= YES;
}
但我的应用程序始终启动谷歌页面。为什么服务器是零?服务器必须有默认值吗?怎么了?
答案 0 :(得分:0)
根据我的理解,您必须手动设置默认值,否则它们为空。试试这个:
-(void)viewDidLoad {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *server = [defaults objectForKey:@"serverName"];
NSLog(@"%@", server); // <-- should print null
//If the default value is null, set a value
if(server==nil) {
[defaults setObject:@"http://192.168.0.4/portal.aspx" forKey:@"serverName"];
//change your string to reflect the changes.
server = [defaults ObjectForKey:@"serverName"];
NSLog(@"%@", server); // <-- should print your URL
}
[defaults synchronize]; //Saves defaults.
[super viewDidLoad];
[proView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: server]]];
proView.scalesPageToFit= YES;
}