使用存储在数组中的URL从应用程序启动Safari

时间:2012-01-26 08:16:56

标签: ios arrays xcode url safari

这是一个按钮,当点击它将打开Safari。

-(IBAction)loginClicked:(id)sender{
NSLog(@"loginClicked");

NSLog(@"currentSelectedRow = %i", currentSelectedRow );

loginObj = [appDelegate.loginArray objectAtIndex:currentSelectedRow];
NSLog(@"URL = %@", loginObj.loginURL);

Error-->[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"%@", loginObj.loginURL]];

}

错误:Too many arguments to method call, expected 1, have 27

如果我用

替换[[UIApplication sharedApplication]
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"www.google.com"]];

可以启动Safari并转到Google,我的调试器会显示以下内容

2012-01-26 16:04:15.546 Login2[197:707] loginClicked
2012-01-26 16:04:15.550 Login2[197:707] currentSelectedRow = 0
2012-01-26 16:04:15.555 Login2[197:707] URL = www.amazon.com

我似乎已正确地从我的数组中提取URL但我无法将其实现到代码中以在Safari中打开URL

2 个答案:

答案 0 :(得分:1)

Error-->[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"%@", loginObj.loginURL]];  //Edit this line as
Correct-->[[UIApplication sharedApplication] openURL:[NSURL URLWithString:loginObj.loginURL]];

答案 1 :(得分:1)

问题是您正在尝试将格式参数传递给

[NSURL URLWithString:]

但是URLWithString方法不接受格式化参数 - 并非每个在iOS中使用字符串的方法都可以使用[NSSString stringWithFormat:]NSLog()

通常,一个好的线索是,如果方法接受格式化参数,则该方法将被命名为somethingWithFormat:而不是somethingWithString:。您应该假设名为somethingWithString:的方法不接受格式化参数。

要修复代码,请将其拆分为两个调用:

NSString *urlString = [NSSString stringWithFormat:@"%@", loginObj.loginURL];
NSURL *url = [NSURL URLWithString:urlsString];

虽然想到了,但我不确定你为什么不写:

NSURL *url = [NSURL URLWithString:loginObj.loginURL];

因为除了吐出第一个参数之外你实际上没有对格式字符串做任何事情。

相关问题