iOS10中的OpenURL

47

显然,OpenURL在iOS 10中已被弃用。有没有人有关于为什么要这样做的文档或者可以解释接下来该怎么做?我已经在苹果网站上查找了一些与OpenURL相关的东西,而现在他们建议使用以下内容:

所以显然,OpenURL在iOS 10中已经被弃用。是否有关于此举原因的文档或者有人能解释下一步该怎么做呢?我已经在苹果网站上找到了一些关于OpenURL的东西,他们建议现在使用以下内容:

UIApplication.shared().open(url: URL, options: [String: AnyObject], completionHandler: ((Bool) -> Void)?)

有人有证据表明这是在Swift 3.0中使用OpenURL的新方式吗?此外,options:completionHandler:参数分别应使用哪些值?


@LeoDabus 说“打开不可用”。 - Tom Roggero
@TomRoggero http://stackoverflow.com/questions/39402696/swift-3-open-link/39460744#39460744 - Leo Dabus
8个回答

63

Swift 3+:

func open(scheme: String) {
   if let url = URL(string: scheme) {
      if #available(iOS 10, *) {
         UIApplication.shared.open(url, options: [:],
           completionHandler: {
               (success) in
                  print("Open \(scheme): \(success)")
           })
     } else {
         let success = UIApplication.shared.openURL(url)
         print("Open \(scheme): \(success)")
     }
   }
 }

使用方法:

open(scheme: "tweetbot://timeline")

来源


这个示例仅适用于Swift 3.0。太棒了! - Castor
谢谢,我已经适应了它并正在使用。 - James T Snell
请使用以下代码 let success = UIApplication.shared().openURL(url) 而不是 let success = UIApplication.shared.openURL(url)。 - niravdesai21

44

一种快速修复方法:

// Objective-C
UIApplication *application = [UIApplication sharedApplication];
[application openURL:URL options:@{} completionHandler:nil];

// Swift
UIApplication.shared.open(url, options: [:], completionHandler: nil)

一个完整的答案:

http://useyourloaf.com/blog/openurl-deprecated-in-ios10/

Credits: Keith Harrison (useyourloaf.com)


13

一个空的选项字典将会导致与openUrl相同的行为。

否则:

+-------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------+
| UIApplicationOpenURLOptionsSourceApplicationKey | NSString containing the bundle ID of the originating application                                                                             |
+-------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------+
| UIApplicationOpenURLOptionsAnnotationKey        | property-list typed object corresponding to what the originating application passed in UIDocumentInteractionController's annotation property |
+-------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------+
| UIApplicationOpenURLOptionsOpenInPlaceKey       | bool NSNumber, set to YES if the file needs to be copied before use                                                                          |
+-------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------------+

来自UIApplication.h

// Options are specified in the section below for openURL options. An empty options dictionary will result in the same
// behavior as the older openURL call, aside from the fact that this is asynchronous and calls the completion handler rather
// than returning a result.
// The completion handler is called on the main queue.
- (void)openURL:(NSURL*)url options:(NSDictionary<NSString *, id> *)options completionHandler:(void (^ __nullable)(BOOL success))completion NS_AVAILABLE_IOS(10_0) NS_EXTENSION_UNAVAILABLE_IOS("");

UIKIT_EXTERN UIApplicationOpenURLOptionsKey const UIApplicationOpenURLOptionsSourceApplicationKey NS_SWIFT_NAME(sourceApplication) NS_AVAILABLE_IOS(9_0);   // value is an NSString containing the bundle ID of the originating application
UIKIT_EXTERN UIApplicationOpenURLOptionsKey const UIApplicationOpenURLOptionsAnnotationKey NS_SWIFT_NAME(annotation) NS_AVAILABLE_IOS(9_0);   // value is a property-list typed object corresponding to what the originating application passed in UIDocumentInteractionController's annotation property
UIKIT_EXTERN UIApplicationOpenURLOptionsKey const UIApplicationOpenURLOptionsOpenInPlaceKey NS_SWIFT_NAME(openInPlace) NS_AVAILABLE_IOS(9_0);   // value is a bool NSNumber, set to YES if the file needs to be copied before use

5

那个回答问题的有点,但并不完全。openURL:options:completionHandler:是我们应该使用的新函数吗?还是这就是我在问题中提出的建议?在这种情况下,您仍然需要使用UIApplication.shared()... - KSigWyatt
从我所读的内容来看,它明确表明openURL:options:completionHandler:函数是openUrl的替代品。并非所有文档都已更新,有些仍然指向已弃用的代码。 - Yasir
这是您想要发布的链接:https://developer.apple.com/library/prerelease/content/releasenotes/General/WhatsNewIniOS/Articles/iOS10.html#//apple_ref/doc/uid/TP40017084-DontLinkElementID_34 - Fyodor Volchyok

3

加载网址之前需要进行一些检查。请先检查以下代码:

if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"https://www.gmail.com"]]){
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.gmail.com"] options:@{} completionHandler:^(BOOL success) {
                                //completion codes here
                            }];
}

我希望这能有所帮助。

1
如果您的应用程序仍支持iOS 9或更低版本,则继续使用旧的openURL。只有当您的Deployment Target为iOS 10时,才应切换到新的openURL。

1

let actual:

[String: AnyObject] = ["xxx key": "xxx value" as AnyObject, "yyy key": "yyy value" as AnyObject]

UIApplication.shared.open(URL(string: "http:google.com")!, options: actual, completionHandler: {(true) -> Swift.Void in
print("Refresh")
})

其中 xxx 和 yyy 是您想要打印或留空的任何字符串。


0

你可以使用函数打开设置:

func showAlert(title:String, message:String){
        let alert = UIAlertController(title: title,
                                      message: message,
                                      preferredStyle: UIAlertController.Style.alert)

        let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
        alert.addAction(okAction)

        let settingsAction = UIAlertAction(title: "Settings", style: .default, handler: { _ in
            // Take the user to Settings app to possibly change permission.
            guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return }
            if UIApplication.shared.canOpenURL(settingsUrl) {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                        // Finished opening URL
                    })
                } else {
                    // Fallback on earlier versions
                    UIApplication.shared.openURL(settingsUrl)
                }
            }
        })
        alert.addAction(settingsAction)
        present(alert, animated: true, completion: nil)
    }

按照下面的方式调用此函数

showAlert(title: "Unable to access the Photos", message: "To enable access, go to Settings > Privacy > Photos and turn on Photos access for this app.")

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