128

这可能是一个相当明显的问题,但是您可以从 iPhone 应用程序启动 Safari 浏览器吗?

4

7 回答 7

200

应该如下:

NSURL *url = [NSURL URLWithString:@"http://www.stackoverflow.com"];

if (![[UIApplication sharedApplication] openURL:url]) {
    NSLog(@"%@%@",@"Failed to open url:",[url description]);
}
于 2009-08-27T19:40:49.557 回答
53

UIApplication 有一个名为 openURL 的方法:

例子:

NSURL *url = [NSURL URLWithString:@"http://www.stackoverflow.com"];

if (![[UIApplication sharedApplication] openURL:url]) {
  NSLog(@"%@%@",@"Failed to open url:",[url description]);
}
于 2009-05-05T00:25:35.743 回答
16

您可以使用以下方法在 safari 中打开网址:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.google.com"]];
于 2013-03-14T14:16:37.830 回答
4

在 iOS 10 中,我们有一种不同的完成处理程序方法:

目标C:

NSDictionary *options = [NSDictionary new];
//options can be empty
NSURL *url = [NSURL URLWithString:@"http://www.stackoverflow.com"];
[[UIApplication sharedApplication] openURL:url options:options completionHandler:^(BOOL success){
}];

迅速:

let url = URL(string: "http://www.stackoverflow.com")
UIApplication.shared.open(url, options: [:]) { (success) in
}
于 2016-09-21T20:35:11.093 回答
3

在 swift 4 和 5 中,随着 OpenURL 的贬值,一个简单的方法就是

if let url = URL(string: "https://stackoverflow.com") {
    UIApplication.shared.open(url, options: [:]) 
}

您也可以使用SafariServices. 类似于应用程序中的 Safari 窗口。

import SafariServices

...

if let url = URL(string: "https://stackoverflow.com") {
    let safariViewController = SFSafariViewController(url: url)        
    self.present(safariViewController, animated: true)
}

于 2018-04-13T15:10:41.297 回答
3

也许有人可以使用 Swift 版本:

在 Swift 2.2 中:

UIApplication.sharedApplication().openURL(NSURL(string: "https://www.google.com")!)

和 3.0:

UIApplication.shared().openURL(URL(string: "https://www.google.com")!)
于 2016-06-28T17:59:33.833 回答
1

在 Swift 3.0 中,你可以使用这个类来帮助你进行交流。框架维护者已弃用或删除了以前的答案。

导入 UIKit

类 InterAppCommunication {
    静态函数 openURI(_ URI: String) {
        UIApplication.shared.open(URL(string: URI)!, options: [:], completionHandler: { (succ: Bool) in print("Complete! Success? \(succ)") })
    }
}
于 2017-06-28T00:46:50.850 回答