iPhone:如何通过编程打开网址

25

我是iPhone新手,想在我的应用程序中打开一个URL链接。如何完成这个任务?请给我提供一些有用的链接和建议。


这个问题已经有更详细的答案了:如何从iOS应用程序启动Safari并打开URL - Top-Master
4个回答

79

显然上面提供的链接已经过时了。这是 UIApplication 类的更新链接。

快速简单的代码片段如下:

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

// Swift
UIApplication.shared.open(URL(string: "http://www.google.com")!, options: [:], completionHandler: nil)

12

更新(2016年):现在最好的方法是实例化并呈现一个SFSafariViewController。这样可以给用户提供Safari的安全性和速度,并且可以访问他们可能已经设置的任何Cookie或Safari功能,而无需离开您的应用程序。

如果您想在Safari中打开URL(并退出您的应用程序),则可以使用UIApplication的openURL方法

如果您更喜欢在您的应用程序内部处理它,请使用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类。


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"];
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接