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:
var fbUrl = NSURL(string: "fb://facebook.com/FacebookPageName")!
var fbUrlWeb = NSURL(string: "https://www.facebook.com/FacebookPageName")!
if (UIApplication.sharedApplication().canOpenURL(fbUrl)) {
// Facebook App installed
UIApplication.sharedApplication().openURL(fbUrl)
} else {
// No Facebook App installed
UIApplication.sharedApplication().openURL(fbUrlWeb)
}
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:
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:
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
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
}
}
}
}
Swift 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
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With