我试图在用户按下Facebook按钮时打开Facebook应用程序或浏览器。
导入代码:
import Foundation
分机代码:
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
}
}
}
}
功能代码:
func fimageTapped()
{
UIApplication.tryURL([
"fb://profile/1357163924", // App
"http://www.facebook.com/1357163924" // Website if app fails
])
}
我收到了错误:
class func tryURL(urls: [String]) {
错误讯息:
“tryURL”的重新声明无效
这是我找到以下代码的地方:Xcode swift link to facebook page
任何人都知道这里有什么问题吗?
答案 0 :(得分:2)
在Swift 3中使用:
let facebookID: String = "000000000000"
let facebookName: String = "name"
let facebookURLID = URL(string: "fb://profile/\(facebookID)")!
let facebookURLWeb = URL(string: "https://m.facebook.com/\(facebookName)?id=\(facebookID)")!
if(UIApplication.shared.canOpenURL(facebookURLID)){
UIApplication.shared.openURL(facebookURLID)
} else {
UIApplication.shared.openURL(facebookURLWeb)
}
请记住,从iOS 9和10开始,您需要在Info.plist
:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fb</string>
</array>
有了这个,Facebook方案的查询不会因为权限错误而失败:
"This app is not allowed to query for scheme fb"
答案 1 :(得分:0)
使用它,工作正常:
var fbURLWeb: NSURL = NSURL(string: "https://www.facebook.com/ID")!
var fbURLID: NSURL = NSURL(string: "fb://profile/ID")!
if(UIApplication.sharedApplication().canOpenURL(fbURLID)){
// FB installed
UIApplication.sharedApplication().openURL(fbURLID)
} else {
// FB is not installed, open in safari
UIApplication.sharedApplication().openURL(fbURLWeb)
}
答案 2 :(得分:0)
斯威夫特3:
重要: UIApplication是在UIKit中声明的,所以请确保您导入UIKit。
import Foundation
import UIKit
extension UIApplication {
class func tryURL(_ urls: [String]) {
let application = UIApplication.shared
for url in urls {
if application.canOpenURL(URL(string: url)!) {
application.open(URL(string: url)!, options: [:], completionHandler: nil)
return
}
}
}
}
此外:
application.openURL(NSURL(string: url)!)
将 Swift 3 更改为打开并使用completionHandler:
application.open(URL(string: url)!, options: [:], completionHandler: nil)
你的viewController中的下一步:在viewDidLoad上面声明你的facebook应用程序和web-url并创建一个函数或IBAction函数,你可以在其中进行UIapplication.tryURL:
import UIKit
class ViewController: UIViewController {
let fbAppUrl = "facebook://profile/yourFBprofileID"
let fbWebUrl = "https://www.facebook.com/yourFBprofileID"
override func viewDidLoad() {
super.viewDidLoad()
}
func openFacebook() {
UIApplication.tryURL([fbAppUrl, fbWebUrl])
}
}
首先iOS会尝试打开fbAppUrl,但如果设备上没有安装facebook应用程序,它将在Safari中打开fbWebUrl。
答案 3 :(得分:0)
对于Swift 4
let webURL: NSURL = NSURL(string: "https://www.facebook.com/ID")!
let IdURL: NSURL = NSURL(string: "fb://profile/ID")!
if(UIApplication.shared.canOpenURL(IdURL as URL)){
// FB installed
UIApplication.shared.open(webURL as URL, options: [:], completionHandler: nil)
} else {
// FB is not installed, open in safari
UIApplication.shared.open(webURL as URL, options: [:], completionHandler: nil)
}