使用字符串变量打开NSURL - iPhone

时间:2011-04-02 12:40:19

标签: iphone objective-c nsurl

我有一个名为storedURL的变量,其格式为www.xxxxx.com。我试图使用以下代码在用户点击按钮时在Safari中打开此URL。

-(IBAction)launchWeb {

    NSString *url = [NSString stringWithFormat: @"%@",
                     storedURL];

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];  
}

但是,单击该按钮时应用程序崩溃。

任何人都可以帮忙更正我的代码吗?

修改

mvds'代码崩溃如下:

2011-04-02 14:01:41.542 London [16791:207] + [NSURL urlWithString:]:无法识别的选择器发送到类0x103dcbc 2011-04-02 14:01:41.545伦敦[16791:207] *由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:'+ [NSURL urlWithString:]:无法识别的选择器发送到类0x103dcbc' * 在第一次投掷时调用堆栈: (     0 CoreFoundation 0x00fd95a9 exceptionPreprocess + 185     1 libobjc.A.dylib 0x0112d313 objc_exception_throw + 44     2 CoreFoundation 0x00fdb17b + [NSObject(NSObject)doesNotRecognizeSelector:] + 187     3 CoreFoundation 0x00f4a966 __ 转发 + 966     4 CoreFoundation 0x00f4a522 _CF_forwarding_prep_0 + 50     5伦敦0x00006bce - [DetailViewController launchWeb] + 126     6 UIKit 0x0022b4fd - [UIApplication sendAction:to:from:forEvent:] + 119     7 UIKit 0x002bb799 - [UIControl sendAction:to:forEvent:] + 67     8 UIKit 0x002bdc2b - [UIControl(内部)_sendActionsForEvents:withEvent:] + 527     9 UIKit 0x002bc7d8 - [UIControl touchesEnded:withEvent:] + 458     10 UIKit 0x004be4de _UIGestureRecognizerSortAndSendDelayedTouches + 3609     11 UIKit 0x004bec53 _UIGestureRecognizerUpdateObserver + 927     12 CoreFoundation 0x00fba89b CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION + 27     13 CoreFoundation 0x00f4f6e7 __CFRunLoopDoObservers + 295     14 CoreFoundation 0x00f181d7 __CFRunLoopRun + 1575     15 CoreFoundation 0x00f17840 CFRunLoopRunSpecific + 208     16 CoreFoundation 0x00f17761 CFRunLoopRunInMode + 97     17 GraphicsServices 0x0151a1c4 GSEventRunModal + 217     18 GraphicsServices 0x0151a289 GSEventRun + 115     19 UIKit 0x00239c93 UIApplicationMain + 1160     20伦敦0x00001ee9主+ 121     21伦敦0x00001e65开始+ 53

1 个答案:

答案 0 :(得分:6)

网址可能是nil,因为“www.xxxxxxx.com”不是网址。尝试

 NSString *urlstring = [NSString stringWithFormat:@"http://%@/",storedURL];
 NSURL *url = [NSURL URLWithString:urlstring];
 NSLog(@"url = %@",url);
 [[UIApplication sharedApplication] openURL:url];

如果这没有帮助,请分享控制台窗口中给出的输出(堆栈跟踪)。