简体   繁体   English

iPhone:以编程方式打开网址

[英]iPhone: Open a url Programmatically

I am new to iPhone. 我是iPhone新手。 I want to open an url in my application. 我想在我的应用程序中打开一个URL。 How can I do this task? 我该怎么做这个任务? Please suggest me and provide some useful link. 请建议我并提供一些有用的链接。

Apparently the link given above is outdated. 显然上面给出的链接已经过时了。 Here is the update link for the UIApplication class. 这是UIApplication类的更新链接。

The quick and simple code snippet is: 快速简单的代码段是:

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

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

Update (2016): The best way to do this nowadays is to instantiate and present an SFSafariViewController. 更新(2016):现在最好的方法是实例化并呈现SFSafariViewController。 This gives the user the security and speed of Safari, and access to any cookies or Safari features they may already have set without having to leave your app. 这为用户提供了Safari的安全性和速度,并且可以访问他们可能已经设置的任何Cookie或Safari功能,而无需离开您的应用。

If you want to open the URL in Safari (and exit your application) you can use the openURL method of UIApplication 如果要在Safari中打开URL(并退出应用程序),可以使用UIApplicationopenURL方法

If you'd rather have it handled inside of your app, use WKWebView. 如果您希望在应用内部处理它,请使用WKWebView。

If you would like to open and just get the data from the URL, you could use NSString: 如果您想打开并从URL获取数据,可以使用NSString:

NSString *ans = [NSString stringWithContentsOfURL:url];

If what you are trying to get is an XML from a URL, you can directly use NSXMLParser: 如果您要获取的是来自URL的XML,则可以直接使用NSXMLParser:

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

On the other hand, if by opening you mean, open a URl in an embedded browser, you could use UIWebView class. 另一方面,如果打开你的意思是在嵌入式浏览器中打开一个URl,你可以使用UIWebView类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM