Xcode 快速链接到 Facebook 页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29376673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Xcode swift link to facebook page
提问by ChallengerGuy
I have an app with a button that is suppose to open a Facebook page. It checks to see if the user has Facebook installed and should open the page in the app. If it is not installed, then it simply opens the page with Safari. It is not working however. I suspect it has something to do with the wrong address for it, if the user has Facebook installed:
我有一个带有按钮的应用程序,可以打开 Facebook 页面。它会检查用户是否安装了 Facebook 并且应该在应用程序中打开页面。如果它没有安装,那么它只是用 Safari 打开页面。但是,它不起作用。如果用户安装了 Facebook,我怀疑它与错误的地址有关:
回答by Ian
The problem is with the format of your Facebook url so notice the format. I use this extension to open urls. You provide it with an array of urls in the order you want them to try to be opened and it tries the first one first and if it fails it goes to the second one and so on:
问题在于您的 Facebook 网址的格式,因此请注意格式。我使用此扩展程序打开网址。您按照您希望它们尝试打开的顺序为它提供一组 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
}
}
}
}
And for use:
并使用:
UIApplication.tryURL([
"fb://profile/116374146706", // App
"http://www.facebook.com/116374146706" // Website if app fails
])
[Update] for Swift 4:
[更新] 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
}
}
}
}
And then:
进而:
UIApplication.tryURL(urls: [
"fb://profile/116374146706", // App
"http://www.facebook.com/116374146706" // Website if app fails
])
[Update] for iOS 10 / Swift 5
[更新] 适用于 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
}
}
}
}
回答by Himanshu Parashar
Swift 3
斯威夫特 3
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)!)
application.open(URL(string: url)!, options: [:], completionHandler: nil)
return
}
}
}
}
And for use:
并使用:
UIApplication.tryURL(urls: [
"fb://profile/116374146706", // App
"http://www.facebook.com/116374146706" // Website if app fails
])