2011-04-02 19 views
3

我有一個名爲storedURL的變量,格式爲www.xxxxx.com。我試圖在用戶點擊按鈕時使用下面的代碼在Safari中打開此URL。使用字符串變量打開NSURL - iPhone

-(IBAction)launchWeb { 

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

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

但是,當按鈕被點擊時,應用程序崩潰。

任何人都可以幫助糾正我的代碼嗎?

EDIT

MVDS'代碼崩潰,以下:

2011-04-02 14:01:41.542倫敦[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 - [U ICONTROL 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

回答

5

的URL可能是nil,因爲 「www.xxxxxxx.com」 是不是URL。嘗試

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

如果這沒有幫助,請共享控制檯窗口中給出的輸出(堆棧跟蹤)。

+0

嗨mvds。謝謝你的幫助。此代碼與上面的堆棧崩潰。還有一個警告,NSURL我沒有迴應urlWithString。 – GuybrushThreepwood 2011-04-02 13:02:55

+0

@Onomycoco,修復方法URLWithString的情況。這將解決這個問題。 – 2011-04-02 13:17:07

+0

第一行仍然崩潰:NSString * urlstring = [NSString stringWithFormat:@「http://%@ /」,storedURL]; – GuybrushThreepwood 2011-04-02 13:21:53