2009-11-01 118 views
23

我是iPhone新手。 我想在我的應用程序中打開一個網址。 我該怎麼做這個任務?請建議我並提供一些有用的鏈接。iPhone:打開網址編程

回答

12

更新(2016):現在做這件事的最好方法是實例化並呈現SFSafariViewController。這爲用戶提供了Safari的安全性和速度,以及訪問他們可能已經設置的任何cookie或Safari功能,而無需離開您的應用。

如果你想在Safari中打開的網址(和退出應用程序),您可以使用openURL method of UIApplication

如果你寧願有它您的應用程序的內部處理,使用WKWebView。

5

如果你想打開,只是得到的URL數據,你可以使用NSString:

NSString *ans = [NSString stringWithContentsOfURL:url]; 

如果你正在試圖獲得來自URL的XML,你可以直接使用的NSXMLParser :

NSURL *url = [[NSURL alloc] initWithString:urlstr]; 
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url]; 
// parse here 
[parser release]; 
[url release]; 

在另一方面,如果通過打開你的意思是,在嵌入式瀏覽器打開一個URL,你可以使用UIWebView類。

76

顯然上面給出的鏈接已經過時。這是UIApplication類的更新鏈接。

快速和簡單的代碼片段是:

// ObjC 
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://www.google.com"]]; 

// Swift 
UIApplication.shared.open(URL(string: "http://www.google.com")!, options: [:], completionHandler: nil) 
3
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"https://medium.com/the-traveled-ios-developers-guide/swift-3-feature-highlight-c38f94359731#.83akhtihk"]]) { 
       [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://medium.com/the-traveled-ios-developers-guide/swift-3-feature-highlight-c38f94359731#.83akhtihk"]]; 
      } 
      else{ 
       [SVProgressHUD showErrorWithStatus:@"Please enable Safari from restrictions to open this link"]; 
      }