2009-11-01 116 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"]; 
      }