一尘不染

Xcode快速链接到Facebook页面

swift

我有一个带有按钮的应用程序,该应用程序可以打开Facebook页面。它检查用户是否已安装Facebook,并应在应用程序中打开页面。如果未安装,则仅使用Safari打开页面。但是,它不起作用。如果用户安装了Facebook,我怀疑这与地址错误有关:


阅读 313

收藏
2020-07-07

共1个答案

一尘不染

问题在于您的Facebook
URL的格式,因此请注意格式。我使用此扩展名打开网址。您以希望它们尝试打开的顺序为它提供了一组URL,它首先尝试第一个,如果失败,则转到第二个,依此类推:

extension UIApplication {
    class func tryURL(urls: [String]) {
        let application = UIApplication.sharedApplication()
        for url in urls {
            if application.canOpenURL(NSURL(string: url)!) {
                application.openURL(NSURL(string: url)!)
                return
            }
        }
    }
}

和使用:

UIApplication.tryURL([
            "fb://profile/116374146706", // App
            "http://www.facebook.com/116374146706" // Website if app fails
            ])

Swift 4的[更新]:

extension UIApplication {
    class func tryURL(urls: [String]) {
        let application = UIApplication.shared
        for url in urls {
            if application.canOpenURL(URL(string: url)!) {
                application.openURL(URL(string: url)!)
                return
            }
        }
    }
}

然后:

UIApplication.tryURL(urls: [
                "fb://profile/116374146706", // App
                "http://www.facebook.com/116374146706" // Website if app fails
                ])

[更新]适用于iOS 10 / Swift 5

extension UIApplication {
    class func tryURL(urls: [String]) {
        let application = UIApplication.shared
        for url in urls {
            if application.canOpenURL(URL(string: url)!) {
                if #available(iOS 10.0, *) {
                    application.open(URL(string: url)!, options: [:], completionHandler: nil)
                }
                else {
                    application.openURL(URL(string: url)!)
                }
                return
            }
        }
    }
}
2020-07-07